我的任务是迁移 2 个独立的模块,以与 Java 7 编译和运行时兼容。我想知道我是否考虑了所有因素(即 future 是否会产生许多副作用、限制等)。
这些模块称为 ModuleA 和 ModuleB,结构如下:
ModuleA <- Runtime Library
\-pack1 <- This contains ~15 interfaces, ~3 layers of inheritance, and occasionally static/default methods
\-pack2 <- This contains some standard implementations of interfaces in package1
ModuleB <- Main app. Depends on ModuleA
\-main <- Classes here call static/default ModuleA.package1.* interface methods a lot
ModuleB 可以定期更改,而 ModuleA 是专有/内部 API,不太可能更改。将源代码转换为 Java 7 兼容性的过程给我带来了一些麻烦。
我最初计划的方法是在每个接口(interface)内部创建一个静态内部类,并迁移内部类内部的静态和默认方法,将它们全部更改为static
。在更改签名/实现后,我将通过将实例作为第一个参数添加到参数列表中来标记(以前的)默认方法,然后添加注释@Default (所以我会知道如何翻译 ModuleB 中的实现)。所以这个:
interface Foo {
void doFoo(String bar);
default String toFancyString() {
return this.toString() + "called from a default method";
}
static int getFooDefault() {
return 0xCAFEBABE;
}
}
将更改为:
interface Foo {
void doFoo(String bar);
final class Util {
@Default
static String toFancyString(Foo impl) {
return impl.toString() + "called from a default method";
}
static int getFooDefault() {
return 0xCAFEBABE;
}
}
}
更改两个 ModuleA 包后,我将 ModuleB (在编译时)更改为与更改此内容等效的值:
int i = foo.getFooDefault() + 1;
Foo f = bar -> System.out.println(bar);
String fancyString = f.toFancyString();
对此:
int i = Foo.Default.getFooDefault() + 1;
Foo f = // anonymous class bloat here
String fancyString = Foo.Default.toFancyString(f);
我想知道的是:
更改 ModuleA.package1 时如何模拟接口(interface)继承?由于
Util
类中的方法都是静态的,所以我考虑将所有静态方法添加到存在父类(super class)方法的子类中,并从子类静态中手动调用最接近的上链静态方法方法,但可能有更简单的解决方案。如果我自动化第二部分(ModuleB - 可能经常更改的代码),是否会出现无法编译的情况?
代码行数/复杂性并不重要,因为我可以编写大部分源转换的脚本。我的目标只是在 JRE7 中运行时能够产生与在 8 中相同的输入/输出,不使用任何反射/鸭子类型。 (另外,我只担心静态/默认问题,而不担心任何新的 JDK8 API)
最佳答案
将jdk-8迁移到jdk-7,在接口(interface)上使用默认方法/静态方法。您可以用抽象类替换接口(interface)。那么使用您迁移的模块的其他模块不需要修改。例如:
abstract class Foo {
public abstract void doFoo(String bar);
public String toFancyString() {
return this.toString() + "called from a default method";
}
public static int getFooDefault() {
return 0xCAFEBABE;
}
}
但是,当你使用java Proxy时引入抽象类并将所有静态方法下拉到抽象类中还有另一个原因API。然后让所有已实现的类 Foo
扩展 AbstractFoo
,例如:
interface Foo {
void doFoo(String bar);
String toFancyString();
}
abstract class AbstractFoo implements Foo {
public String toFancyString() {
return this.toString() + "called from a default method";
}
static int getFooDefault() {
return 0xCAFEBABE;
}
}
class SimpleFoo extends AbstractFoo {
@Override
public void doFoo(String bar) {/*todo*/}
}
注意:第二种方式调用静态方法时,由于静态方法所在位置发生了变化,其他模块需要修改。
关于java - 我正在尝试转换 2 个使用 Java8 语言功能的模块,如何模仿静态/默认方法行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880947/