How to create an instance out of a TypeMirror

瘦欲@ 提交于 2019-12-02 10:40:47

During annotation processing, in the general case it is not possible to construct an instance of any class being compiled. Remember that annotation processing runs inside the compiler, as a part of a multi-step process. There's no guarantee that a class and all its dependencies are actually compiled and ready to class-load at the time your annotation processor is executing.

Note also that your annotation declaration is invalid. Section 9.6.1 of the Java language specification lists the valid types of annotation elements, and a value of an user-defined interface is not one of them. At best what you can have is a Class<? extends MyInterface>, but then you have the same issues about how to instantiate it.

It sounds like your use case for annotation processing is very specialized. It would probably help if you opened a new question about the actual problem you're trying to solve, since there may be a better way to solve it than this.

Erik Hofer

There was an answer by Will Lp that he deleted because it was related to Groovy and not to Java.

I do, however, think that it is relevant nonetheless.

When using Groovy you can actually pass a closure as a class parameter to an annotation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!