Why does isAnnotationPresent work differently between Java 7 and Java 8?

后端 未结 1 1304
南旧
南旧 2021-01-05 16:23

I just discovered this today when one of my unit tests failed because of upgrading from Java 7 to Java 8. The unit test calls a method which tries to find an annotation on a

相关标签:
1条回答
  • 2021-01-05 17:03

    I believe this is related to a change mentioned in the java 8 compatibility guide

    As of this release, parameter and method annotations are copied to synthetic bridge methods.This fix implies that now for programs like:

    @Target(value = {ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME) @interface ParamAnnotation {}  
    @Target(value = {ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME) @interface MethodAnnotation {}  
    abstract class T<A,B> {
        B m(A a){
            return null;
        }  
    }    
    class CovariantReturnType extends T<Integer, Integer> {
        @MethodAnnotation
        Integer m(@ParamAnnotation Integer i) {
            return i;
        }
    
        public class VisibilityChange extends CovariantReturnType {}   
    }  
    

    Each generated bridge method will have all the annotations of the method it redirects to. Parameter annotations will also be copied. This change in the behavior may impact some annotations processor or in general any application that use the annotations.

    The second method that returns an I instead of an IE is a synthetic method generated because you have a narrower return type in the overridden method than in the super class. Note that it's not present in the list of declared methods if you don't have a narrowing return type. So I think this is not a bug, but a deliberate change.

    0 讨论(0)
提交回复
热议问题