Issue
I have an annotation-processor
java app that is looking into the target
folder of the external maven project for the class files. This app uses URLClassLoader
. The target folder is the absolute path app parameter. I have a simple junit test which is loading classes and processing the annotations successfully. Now I wrote the maven plugin that is just a wrapper for annotation-processor
app. When running this maven plugin, annotation-processor
loads the classes but it does not see any annotations in those. How can I access class/interface annotations from the maven plugin?
- maven-plugin-plugin:3.6.4
- java 11.0.15
private static Class<?> getClass(String path, String className, String packageName) {
File file = new File(path);
try {
URL[] urls = new URL[]{file.toURI().toURL()};
ClassLoader cl = new URLClassLoader(urls);
return cl.loadClass(packageName + "." + className));
} catch (MalformedURLException | ClassNotFoundException e) {
log.warn("Cannot find class: " + packageName + "." + className, e);
}
return null;
}
Example call:
Class clazz = getClass("/home/user/java/my-project/target/classes", "MyClass", "com.my.example.package");
assert clazz.getAnnotations() > 0;
Solution
There are two possible reasons:
- your annotations do not have proper
@Retention
- JVM silently drops information about annotations while loading the class - that may happen if classloader does know nothing about annotation classes - that is very likely your case because you are instantiating new classloader without specifying parent
Answered By - Andrey B. Panfilov
Answer Checked By - Willingham (JavaFixing Volunteer)