简体   繁体   中英

Scan custom annotated classes from maven plugin

I have a "simple maven project" that contains a package with some custom annotated classes. I'm currently developing a maven plugin that can scan my "simple project" for those annotated classes and then return their name and the associated package.

For exemple : simple-project/src/main/java/myApp/domain/Entity.java with Entity annotated with @MyCustomAnnotation and the "my-maven-plugin" project is declared in the "simple-project" pom.xml

So, if I run "mvn generator:myGoal" it should generate a file with this content : myApp.domain.Entity

I tried almost everything I found on the internet but nothing really worked. Everytime I run my goal, my plugin scans for its own classes but not my simple-project classes.

Any help would be appreciated.

Thanks.

I found a solution. I loop on the sourceDirectory with a recursive function to find all files. Here is how I get the sourceDirectory from my mojo :

/**
     * Project's source directory as specified in the POM.
     * 
     * @parameter expression="${project.build.sourceDirectory}"
     * @readonly
     * @required
     */
    private final File sourceDirectory = new File("");
    fillListWithAllFilesRecursiveTask(sourceDirectory);

I get the path of those files and then I use com.google.code.javaparser to parse the associated FileInputStream.

public void fillListWithAllFilesRecursiveTask(final File root) {
                    CompilationUnit cu;
                    FileInputStream in;
                    try {
                        // we looped through root and we found a file (not a directory)
                        in = new FileInputStream(file);
                        cu = JavaParser.parse(in);
                        new MethodVisitor().visit(cu, file);

Finally, I extend the VoidVisitorAdapter to get Annotations and members...etc

private static class MethodVisitor extends VoidVisitorAdapter<File> {

        @Override
        public void visit(ClassOrInterfaceDeclaration n, File file) {
            if (n.getAnnotations() != null) {
                // store classes that are annotated
                for (AnnotationExpr annotation : n.getAnnotations()) {
                    //here some logic
                    }
                } ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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