java - 执行 Java AnnotationProcessor 时出现 ClassNotFound 异常

标签 java annotations

我编写了一个简单的注释和一个 AnnotationProcessor 来处理注释。

注释只有一个值:它应该是现有接口(interface)的名称(带包)。

注释处理器应该检索注释的值,检索接口(interface)的 Class 对象,最后应该打印接口(interface)中声明的所有方法。

示例: 这是我的注释

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.CLASS)
public @interface MyAnnotation{
    public String interfaceName();
}

这是带注释的类:

@MyAnnotation(interfaceName = "java.lang.CharSequence")
public class Example{}

我的处理器看起来像

[...]
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {

    for (TypeElement te : annotations) {

        for(Element e : env.getElementsAnnotatedWith(te)) {

            MyAnnotation myAnnotation = e.getAnnotation(MyAnnotation.class);
            String iName = myAnnotation.interfaceName();
            Class<?> clazz = Class.forName(iName);
            // use reflection to cycle through methods and prints them
            [...]
        }
    }

现在,如果我将 java.lang.CharSequence 这样的接口(interface)配置为 MyAnnotation 的接口(interface)名称,那么效果很好;

但是,如果我将位于 .jar 文件(添加到项目的构建路径中)中的接口(interface)配置为 interfaceName,则当我尝试执行 Class.forName(...) 语句时,我会收到 ClassNotFoundException。

有什么想法吗?

谢谢你, 干杯

最佳答案

这是一个典型的类加载器问题。您试图查找当前类加载器未加载的类,因此会引发 ClassNotFoundException

Javadoc for java.lang.Class 将方法 Class.forName(className) 定义为:

Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to Class.forName(className, true, currentLoader) where currentLoader denotes the defining class loader of the current class.

因此,此方法调用将尝试在当前类加载器上下文中查找指定的类。您尝试查找的接口(interface)尚未被该类加载器加载,因此会抛出 ClassNotFoundException

如果 .jar 文件位于应用程序的类路径中,则只需使用系统类加载器即可,如下所示...

ClassLoader systemClassLoader = ClassLoader.getSystemClassloader();
Class<?> clazz = Class.forName(className, true, systemClassLoader)

...但是,如果您的 .jar 文件位于其他位置,并且尚未加载,则您需要相应地加载它:

ClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("path/to/file.jar")});
Class<?> clazz = Class.forName(className, true, urlClassLoader)

瞧瞧!

关于java - 执行 Java AnnotationProcessor 时出现 ClassNotFound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57255374/

相关文章:

java - 使用 arraylist 和 foreach 时如何避免内存泄漏?

go - beego中可以使用多个注解吗?

java - 从 AnnotationMirror 获取元素注释

java - 自动(半)创建单元测试?

Spring AOP : Replace XML with annotations for transaction management?

mysql - 具有多个索引的学说 2

java - 如何使用java spring允许跨源请求

java - 如何将 Jar 依赖项添加到 Java Google App Engine 项目?

java - 无法使用附加的探查器运行 jvm

java - 如果用户输入在 Java 中按时间顺序排列,如何迭代数组