Reputation: 61
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?
Upvotes: 4
Views: 1559
Reputation: 61
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
}
Upvotes: 2