Java 的编译器不保留通用方法注释?

Java's compiler not retaining generic method annotations?

我目前遇到 Java 的通用类型擦除和运行时注释的问题,我不确定是我做错了什么还是 Java 编译器中的错误。考虑以下最小工作示例:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
}

public interface MyGenericInterface<T> {
    void hello(T there);
}

public class MyObject {
}

public class MyClass implements MyGenericInterface<MyObject> {
    @Override
    @MyAnnotation
    public void hello(final MyObject there) {
    }
}

现在,当我使用反射查询有关 MyClass.hello 的信息时,我希望 hello 方法仍然具有注释,但它没有:

public class MyTest {

    @Test
    public void testName() throws Exception {
        Method[] declaredMethods = MyClass.class.getDeclaredMethods();
        for (Method method : declaredMethods) {
            Assert.assertNotNull(String.format("Method '%s' is not annotated.", method), method
                    .getAnnotation(MyAnnotation.class));
        }
    }

}

(意外的)错误信息如下:

java.lang.AssertionError: Method 'public void test.MyClass.hello(java.lang.Object)' is not annotated.

使用 Java 1.7.60 进行测试。

该方法出现了两次。一个有注释,另一个没有。我想这也是你的情况,但断言错误发生在坏的,你看不到好的。

Method[] declaredMethods = MyClass.class.getDeclaredMethods();
for (Method method : declaredMethods) {
    System.out.println(String.format("Method: %s", method));
    for (Annotation a: method.getAnnotations()) {
        System.out.println(String.format("  Annotation: %s  of class %s", a, a.annotationType()));
    }
    for (Annotation a: method.getDeclaredAnnotations()) {
        System.out.println(String.format("  DeclaredAnnotation: %s  of class %s", a, a.annotationType()));
    }
    if (method.getDeclaredAnnotation(MyAnnotation.class) == null) {
        System.out.println(String.format(
                "  Method '%s' is not annotated.", method));
    }
}

输出为:

Method: public void MyClass.hello(MyObject)
  Annotation: @MyAnnotation()  of class interface MyAnnotation
  DeclaredAnnotation: @MyAnnotation()  of class interface MyAnnotation
Method: public void MyClass.hello(java.lang.Object)
  Method 'public void MyClass.hello(java.lang.Object)' is not annotated.

编辑:正如我所预料和其他人所证实的那样,他的方法被编译器复制了。 java 需要它。我 decompile 以正确的方式做到了:

//# java -jar ........\cfr_0_101.jar MyClass --hidebridgemethods false
/*
 * Decompiled with CFR 0_101.
 */
import MyAnnotation;
import MyGenericInterface;
import MyObject;

public class MyClass
implements MyGenericInterface<MyObject> {
    @MyAnnotation
    @Override
    public void hello(MyObject there) {
    }

    @Override
    public /* bridge */ /* synthetic */ void hello(Object object) {
        MyClass myClass;
        myClass.hello((MyObject)object);
    }
}

与这个问题有关:Passing Derived Class to a method which needs to override expecting a base class

我觉得这也有关系。该字段是重复的,因为该方法是: Duplicated field in generated XML using JAXB

似乎在内部,javac 已经创建了 2 个方法:

$ javap -c MyClass.class 
Compiled from "MyTest.java"
class MyClass implements MyGenericInterface<MyObject> {
  MyClass();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."    <init>":()V
       4: return

  public void hello(MyObject);
    Code:
       0: return

  public void hello(java.lang.Object);
    Code:
       0: aload_0
       1: aload_1
       2: checkcast     #2                  // class MyObject
       5: invokevirtual #3                  // Method hello:(LMyObject;)V
       8: return
}

hello(java.lang.Object)方法检查对象的类型,然后调用MyObject方法,上面有注解。


更新

我看到这些额外的 "bridge methods" 作为类型擦除和泛型的一部分被特别调用:

https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html

此外,这些桥接方法中缺少注释 is a bug which is fixed in Java 8 u94

正如其他人所指出的,编译会生成两个同名方法,一个 hello(Object) 和一个 hello(MyObject)

原因是类型擦除:

MyGenericInterface mgi = new MyClass();
c.hello( "hahaha" );

上面应该可以编译,因为 void hello(T) 的擦除是 void hello(Object)。当然它也应该在运行时失败,因为没有接受任意 Object.

的实现

从上面我们可以得出结论,void hello(MyObject) 实际上不是该方法的有效覆盖。但是如果你不能 "override" 一个带有类型参数的方法,那么泛型就真的没用了。

编译器绕过它的方法是生成一个带有签名 void hello(Object) 的合成方法,它在运行时检查输入参数类型,如果检查成功则委托给 void hello(MyObject)。正如您在 .

中的字节码中看到的

所以你的 class 真的看起来像这样(观察你的注释如何保留在原始方法上):

public class MyClass implements MyGenericInterface<MyObject> {
     @MyAnnotation
     public void hello(final MyObject there) {
     }

     @Override
     public void hello(Object ob) {
         hello((MyObject)ob);
     }
}

幸运的是,因为它是一个合成方法,你可以通过检查 method.isSynthetic() 的值来过滤掉 void hello(Object),如果它是真的,你应该为了注释处理的目的而忽略它。

@Test
public void testName() throws Exception {
    Method[] declaredMethods = MyClass.class.getDeclaredMethods();
    for (Method method : declaredMethods) {
        if (!method.isSynthetic()) {
             Assert.assertNotNull(String.format("Method '%s' is not annotated.", method), method
                .getAnnotation(MyAnnotation.class));
        }
    }
}

这应该可以正常工作。

更新: 根据 this RFE,注释现在也应该复制到桥接方法中。