Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a class from annotations processor in eclipse?

I implemented an Annotation Processor and I'm trying to load a class that is referenced by some nested element of the current file being processed, for example the return type of a method.

When I run this code from command line with javac and passing the current project classpath it successfully runs, but when using eclipse I'm getting a ClassNotFoundException. See the example below:

public class MyAnnotationProcessor extends AbstractProcessor {

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    for (TypeElement element : annotations) {
        try {
            TypeElement type = getMethodReturnType(element);
            Class<?> class1 = Class.forName(type.getQualifiedName().toString());
            // ..
            // do some processing with class1
            // ...

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return false;
}

I found that in eclipse the processor doesn't have the classpath of the current project. I could create an URLClassLoader to load those required classes but can't find a way to get the current project path.

Is there a way to get the project path from the annotation processor?

like image 776
Abraham Avatar asked Sep 19 '25 14:09

Abraham


1 Answers

I give up on this one, it seems that you shouldn't be loading referenced classes from the annotation processor. Instead you should use typeUtils and elementUtils from the Processing Environment for anything you need.

It seems that you can do anything but invoke code in the referenced class, for example, to verify a given type implements some interface:

TypeMirror interfaceType = processingEnv.getElementUtils().getTypeElement("my.interfaceType").asType();
if(processingEnv.getTypeUtils().isAssignable(type, interfaceType)){
// do something
}
like image 195
Abraham Avatar answered Sep 22 '25 03:09

Abraham