编写maven插件时,无法读取类注解信息的解决办法


需要编写maven插件,读取指定目录下的类,生成配置文件等信息,达到配置压缩的目的。


遇到了一个问题:


在maven插件类中始终无法读取到配置的注解,无法初始化,最终原因找到如下:


错误的代码:

try {
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

    // This URL for a directory will be searched *recursively*
    URL classes = new URL( "file:///D:/DEV/workspace/chz_workspace/maven-plugin-demo/target/classes/" );

    ClassLoader custom = new URLClassLoader( new URL[] { classes }, systemClassLoader );

    // this class should be loaded from your directory
    Class< ? > clazz = custom.loadClass( "com.chz.apps.web.controller.IndexController" );
    clazz.newInstance();
    System.out.println(clazz.getDeclaredAnnotations().length);
    for (Annotation annotation:clazz.getDeclaredAnnotations()) {
        System.out.println(annotation.annotationType().equals(MultiDataSource.class));
    }
}catch (Exception e){
    e.printStackTrace();
}



正确的代码:

try {
    // This URL for a directory will be searched *recursively*
    URL classes = new URL( "file:///D:/DEV/workspace/chz_workspace/maven-plugin-demo/target/classes/" );

    ClassLoader custom = new URLClassLoader( new URL[] { classes }, Thread.currentThread().getContextClassLoader() );//从上下文线程中初始化,引用的类引用存在于线程中

    // this class should be loaded from your directory
    Class< ? > clazz = custom.loadClass( "com.chz.apps.web.controller.IndexController" );
    clazz.newInstance();
    System.out.println(clazz.getDeclaredAnnotations().length);
    for (Annotation annotation:clazz.getDeclaredAnnotations()) {
        System.out.println(annotation.annotationType().equals(MultiDataSource.class));
    }
}catch (Exception e){
    e.printStackTrace();
}




原创不易,打赏点赞!


gongstring-微信付款码.png gongstring-支付宝付款码.jpg

上一篇 下一篇

分享

热门文章