接口方法的注释在Java 7中继承,但在Java 8中没有

lea*_*qui 18 java eclipse eclipse-jdt java-7 java-8

我正在从Java 7迁移到Java 8,我已经遇到了这种语言的变化.

我有一个带有注释方法的Superinterface:

public interface SuperInterface {

  @X
  SuperInterface getSomething();
}
Run Code Online (Sandbox Code Playgroud)

我有一个SubInterface与相同的注释方法,但返回一个子接口:

public interface SubInterface extends SuperInterface {

  @X
  SubInterface getSomething();
}
Run Code Online (Sandbox Code Playgroud)

当我运行此测试时,它在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);
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

接口方法的注释在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 {  
}
Run Code Online (Sandbox Code Playgroud)

Eug*_*ene 21

至于我可以告诉它应该工作在至少构建Java-8 94,根据.因此这是一个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());
        }
    }
Run Code Online (Sandbox Code Playgroud)

但同样这应该有效,因为错误清楚地说明:运行时保留的注释应该由javac复制到桥接方法.

输出javac:

Present :getSomething isBridge? false
Present :getSomething isBridge? true
Run Code Online (Sandbox Code Playgroud)

输出eclipse compiler:

Present :getSomething isBridge? false
Not present getSomething isBridge? true
Run Code Online (Sandbox Code Playgroud)

  • @Holger`我测试了beta132和update121之间的所有JDK`你的机器上有所有JDK吗?真是太棒了! (3认同)
  • 也许"所有"有点委婉.我有所有相关的更新,这些更新允许得出结论通过它们的代码也将与(未发布的)中间版本一起使用.更新号码系统使它看起来比实际更多.更有趣的部分是脚本,它们遍历所有脚本以编译和运行测试程序...... (3认同)
  • @Holger这是我评论以来唯一能想到的东西!脚本!!! 我立刻想到为自己创造这样的东西 (3认同)
  • OMG,我测试了beta132和update121之间的所有JDK,得出的结论是不能复现,但是我应该测试过beta94之前的版本…… (2认同)

gre*_*449 10

对于Eclipse ecj编译器,这看起来像Eclipse bug 495396,它引用了JDK 6695379.

它标记为4.7的目标,但4.7已经处于候选发布状态,所以我猜它没有进入.