How to create an instance of an annotation

前端 未结 8 1206
无人及你
无人及你 2021-01-30 12:47

I am trying to do some Java annotation magic. I must say I am still catching up on annotation tricks and that certain things are still not quite clear to me.

So... I hav

8条回答
  •  执念已碎
    2021-01-30 13:09

    You can use sun.reflect.annotation.AnnotationParser.annotationForMap(Class, Map):

    public @interface MyAnnotation {
        String foo();
    }
    
    public class MyApp {
        public MyAnnotation getInstanceOfAnnotation(final String foo) {
            MyAnnotation annotation = AnnotationParser.annotationForMap(
                MyAnnotation.class, Collections.singletonMap("foo", "myFooResult"));
        }
    }
    

    Downside: Classes from sun.* are subject to change in later versions (allthough this method exists since Java 5 with the same signature) and are not available for all Java implementations, see this discussion.

    If that is a problem: you could create a generic proxy with your own InvocationHandler - this is exactly what AnnotationParser is doing for you internally. Or you use your own implementation of MyAnnotation as defined here. In both cases you should remember to implement annotationType(), equals() and hashCode() as the result is documented specifically for java.lang.Annotation.

提交回复
热议问题