简体   繁体   English

maven插件处理接口注解

[英]Processing interface annotations by maven plugin

I have an annotation-processor java app that is looking into the target folder of the external maven project for the class files.我有一个annotation-processor java 应用程序正在查看 class 文件的外部 maven 项目的target文件夹。 This app uses URLClassLoader .这个应用程序使用URLClassLoader The target folder is the absolute path app parameter.目标文件夹是绝对路径 app 参数。 I have a simple junit test which is loading classes and processing the annotations successfully.我有一个简单的 junit 测试,它正在加载类并成功处理注释。 Now I wrote the maven plugin that is just a wrapper for annotation-processor app.现在我编写了 maven 插件,它只是annotation-processor应用程序的包装器。 When running this maven plugin, annotation-processor loads the classes but it does not see any annotations in those.运行此 maven 插件时, annotation-processor会加载类,但在这些类中看不到任何注释。 How can I access class/interface annotations from the maven plugin?如何从 maven 插件访问类/接口注释?

  • maven-plugin-plugin:3.6.4行家插件插件:3.6.4
  • java 11.0.15 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;

There are two possible reasons:有两个可能的原因:

  1. your annotations do not have proper @Retention您的注释没有正确的@Retention
  2. 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 JVM 在加载 class 时静默删除有关注释的信息 - 如果类加载器对注释类一无所知 - 这很可能是您的情况,因为您正在实例化新的类加载器而不指定父级

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM