Java的编译器没有保留泛型方法注释?

时间:2015-06-26 09:20:45

标签: java generics reflection 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&#39; public void   test.MyClass.hello(java.lang.Object中)&#39;没有注释。

使用Java 1.7.60进行测试。

3 个答案:

答案 0 :(得分:3)

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

原因是类型擦除:

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

上述内容应该编译,因为void hello(T)的删除是void hello(Object)。当然它也应该在运行时失败,因为没有任何实现可以接受任意Object

从上面我们可以得出结论,void hello(MyObject)实际上并不是该方法的有效覆盖。但是如果你不能覆盖&#34;那么泛型将毫无用处。带有类型参数的方法。

编译器绕过它的方法是生成一个带有签名void hello(Object)的合成方法,该方法在运行时检查输入参数类型,如果检查成功,则委托给void hello(MyObject)。正如您在John Farrelly's answer中的字节代码中所看到的那样。

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

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

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

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

@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,现在也应将注释复制到桥接方法中。

答案 1 :(得分:2)

似乎在内部,javac创建了两种方法:

$ 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方法,该方法上有注释。

<强>更新

我看到这些额外的“桥接方法”被特别称为类型擦除和泛型的一部分:

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

此外,这些桥接方法is a bug which is fixed in Java 8 u94

上缺少注释

答案 2 :(得分:1)

The method appears twice. One is annotated and the other one not. I guess that is your case too but the assertion error happens on the bad one and you can't get to see the good.

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));
    }
}

Output is:

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.

EDIT: As I supossed and others confirmed, he method gets duplicated by the compiler. It is needed by java. I got to decompile it the right way:

//# 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);
    }
}

It is related to this question: Passing Derived Class to a method which needs to override expecting a base class

I think this is related too. The field is duplicated because the method is: Duplicated field in generated XML using JAXB