当exec-maven-plugin运行Main时获取注释

时间:2018-07-23 14:54:52

标签: java maven reflection exec-maven-plugin

我想使用 exec-maven-plugin 运行Main类,并从我的依赖项中生成文档,如swagger文件。

我关心的注释是具有 @Retention(RetentionPolicy.RUNTIME)

的javax.ws.rs.Path。

我的Java代码

public class ContextClassReader extends ClassReader {

private static final ExtensibleClassLoader CLASS_LOADER = new ExtensibleClassLoader();

public ContextClassReader(final String className) throws IOException {
    super(CLASS_LOADER.getResourceAsStream(className.replace('.', '/') + ".class"));
    final URL resource = CLASS_LOADER.getResource(className.replace('.', '/') + ".class");
}

public static ClassLoader getClassLoader() {
    return CLASS_LOADER;
}

public static void addClassPath(final URL url) {
    CLASS_LOADER.addURL(url);
}

private static class ExtensibleClassLoader extends URLClassLoader {

    ExtensibleClassLoader() {
        super(new URL[]{});
    }

    @Override
    public void addURL(final URL url) {
        super.addURL(url);
    }
}

这是加载类并对其进行测试的注释。

final Class<?> clazz = ContextClassReader.getClassLoader().loadClass(className);
isAnnotationPresent(clazz); 

public static boolean isAnnotationPresent(final AnnotatedElement annotatedElement) { 
  ...  annotatedElement.getAnnotations().length  --> 0
  ...  clazz.getMethods().length() ---> works !
}

我的pom.xml

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.6.0</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>java</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <executable>java</executable>
                        <workingDirectory>XXXXXXXXXXXXXXXXXXX</workingDirectory>
                        <addResourcesToClasspath>true</addResourcesToClasspath>
                        <additionalClasspathElements>true</additionalClasspathElements>
                        <includeProjectDependencies>true</includeProjectDependencies>
                        <includePluginDependencies>true</includePluginDependencies>
                        <includeProjectDependencies>true</includeProjectDependencies>

                        <mainClass>XXX.Main</mainClass>
                    </configuration>
                </plugin>

0 个答案:

没有答案