简体   繁体   中英

Instantiate a Class annotated with some annotation

I want to get information about fields from a Class on which a specific annotation is present by getting the annotation in annotation processor.

I can retrieve fully qualified class name from annotation but can't instantiate it, a ClassNotFoundException is being thrown, although class is there.

How can I check if class is not in class path or which classpath is included for annotation processor?

try {
                Class<?> clazz = Class.forName(((TypeElement) e).getQualifiedName().toString());
            } catch (ClassNotFoundException cnfe) {
                cnfe.printStackTrace();
            }

What you're attempting to do in the code in the question is impossible because annotation processing occurs before the program is fully-compiled. That's why you work with eg TypeElement objects instead of Class , because the class is not-yet compiled.

On the other hand, if you just want to examine what sorts of fields are present, you can use the Element API for that , for example:

for (Element e : typeElement.getEnclosedElements()) {
    if (e.getKind() == ElementKind.FIELD) {
        VariableElement field = (VariableElement) e;
        //
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM