我正在从 Java 7 迁移到 Java 8,我遇到了语言的这种变化。
我有一个带有注释方法的 super 接口(interface):
public interface SuperInterface {
@X
SuperInterface getSomething();
}
我有一个带有相同注解方法但返回子接口(interface)的子接口(interface):
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);
}
}
}
}
接口(interface)方法的注解在 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 {
}
最佳答案
据我所知,根据 this,它至少可以 构建 94 的 java-8 .因此,这是一个 eclipse 编译器错误(我无法用 javac
重现它)。
您在这里使用协方差,因此将生成两种方法(一种是桥):
for (Method method : methods) {
if (method.getAnnotations().length == 0) {
System.out.println("Not present " + method.getName() + " isBridge? " + method.isBridge());
} else {
System.out.println("Present :" + method.getName() + " isBridge? " + method.isBridge());
}
}
但这又应该有效,因为该错误清楚地表明:具有运行时保留的注释应由 javac 复制到桥接方法。
用javac
输出:
Present :getSomething isBridge? false
Present :getSomething isBridge? true
用eclipse编译器
输出:
Present :getSomething isBridge? false
Not present getSomething isBridge? true
关于java - 接口(interface)方法的注释在 Java 7 中继承,但在 Java 8 中不继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44136834/