我正在将代码从Java 7迁移到Java 8,遇到了这个语言上的变化。
我有一个具有注解方法的超级接口:
public interface SuperInterface {
@X
SuperInterface getSomething();
}
我有一个带有相同注释方法的SubInterface,但返回的是一个子接口:
public interface SubInterface extends SuperInterface {
@X
SubInterface getSomething();
}
当我运行这个测试时,Java 8会失败,但Java 7不会:
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
final Method[] methods = SubInterface.class.getMethods();
for (Method method : methods) {
if (method.getAnnotations().length == 0) {
throw new RuntimeException("No annotations found for " + method);
}
}
}
}
Java 7中,接口方法的注解是可以被继承的,但在Java 8中不再如此,这是真的吗?
@X被定义为:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface X {
}
SuperInterface
的一个方法是default
方法?在Java7中,它们都是抽象的,但在Java8中,其中一个是default
方法。 - ShadovSubInterface
中的getSomething()
方法,因此没有继承的方法。这是Java 8之前的技术缺陷,在Reflection中可以看到SuperInterface
的擦除方法。在Java 8中(使用javac
),您不会看到任何继承的方法,而是看到两个方法,即覆盖方法和桥接方法。桥接方法将具有覆盖方法的注释,但不会继承SuperInterface.getSomething()
方法的注释。 - Holger