How to create an instance of an annotation

前端 未结 8 1356
无人及你
无人及你 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

    The proxy approach, as suggested in Gunnar's answer is already implemented in GeAnTyRef:

    Map annotationParameters = new HashMap<>();
    annotationParameters.put("name", "someName");
    MyAnnotation myAnnotation = TypeFactory.annotation(MyAnnotation.class, annotationParameters);
    

    This will produce an annotation equivalent to what you'd get from:

    @MyAnnotation(name = "someName")
    

    Annotation instances produced this way will act identical to the ones produced by Java normally, and their hashCode and equals have been implemented properly for compatibility, so no bizarre caveats like with directly instantiating the annotation as in the accepted answer. In fact, JDK internally uses this same approach: sun.reflect.annotation.AnnotationParser#annotationForMap.

    The library itself is tiny and has no dependencies.

    Disclosure: I'm the developer behind GeAnTyRef.

提交回复
热议问题