开发者

Get Class Annotations from Java Source File

I'm parsing Java Source Files to collect various informations about my classes. Therefore I'm using the JavaParser, since I could not find a good alternative (good suggestions have the chance to become "answers") to parse Source Files.

I already managed to get Annotations of all methods from my class. The code looks like this:

package de.mackaz;

import japa.parser.JavaParser;
import japa.parser.ParseException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.expr.AnnotationExpr;
import japa.parser.ast.expr.MarkerAnnotationExpr;
import japa.parser.ast.expr.MemberValuePair;
import japa.parser.ast.expr.NormalAnnotationExpr;
import japa.parser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;

public class JavaSourceUtils {

    public static void main(String[] args) throws Exception {
        File f = new File("/home/mackaz/SourceFile.java");
        inspectJavaFile(f);
    }

    public static void inspectJavaFile(File pFile) 
    throws FileNotFoundException, ParseException, IOException {
        CompilationUnit cu;
        FileInputStream in = new FileInputStream(pFile);
        try {
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        new MethodVisitor().visit(cu, null);
    }

    /**
     * Simple visitor implementation for visiting MethodDeclaration nodes.
     */
    private static class MethodVisitor extends VoidVisitorAdapter {

        @Override
        public void visit(MethodDeclaration n, Object arg) {
            System.out.println(n.getName());
            if (n.getAnnotations() != null) {
                for (AnnotationExpr annotation : n.getAnnotations()) {
                    System.out.println(annotation.getClass());
                    // MarkerAnnotations, for example @Test
                    if (annotation.getClass().equals(MarkerAnnotationExpr.class)) {
                        System.out.println("MarkerAnnotation:" +开发者_StackOverflow ((MarkerAnnotationExpr)annotation).getName());
                    }
                    if (annotation.getClass().equals(NormalAnnotationExpr.class)) {
                        for (MemberValuePair pair : ((NormalAnnotationExpr)annotation).getPairs()) {
                            if (pair.getName().equals("groups"))
                                System.out.println("Group:\"" + pair.getValue() + "\"");
                        }
                    }
                }
            }
        }
    }
}

Now how can I get the Annotations of the class itself?


You are overriding public void visit(MethodDeclaration n, Object arg), which visits methods. You can also override public void visit(ClassOrInterfaceDeclaration n, A arg) or public void visit(ClassOrInterfaceType n, A arg), which should give you access to the information you are looking for.


This is how I solved it in the end - I added another Visitor "ClassVisitor":

private static class ClassVisitor extends VoidVisitorAdapter {
    @Override
    public void visit(ClassOrInterfaceDeclaration n, Object arg) {
        for (AnnotationExpr ann: n.getAnnotations()) {
            System.out.println(ann.toString());
        }
    }
}


Looks like you need extend ModifierVisitorAdapter and implement

public Node visit(ClassOrInterfaceDeclaration n, A arg) {

Look at the implementation here for an idea of what you might want to do:

 public Node visit(ClassOrInterfaceDeclaration n, A arg) {
        if (n.getJavaDoc() != null) {
            n.setJavaDoc((JavadocComment) n.getJavaDoc().accept(this, arg));
        }
        List<AnnotationExpr> annotations = n.getAnnotations();
        if (annotations != null) {
            for (int i = 0; i < annotations.size(); i++) {
                annotations.set(i, (AnnotationExpr) annotations.get(i).accept(this, arg));
            }
            removeNulls(annotations);
        }
        List<TypeParameter> typeParameters = n.getTypeParameters();
        if (typeParameters != null) {
            for (int i = 0; i < typeParameters.size(); i++) {
                typeParameters.set(i, (TypeParameter) typeParameters.get(i).accept(this, arg));
            }
            removeNulls(typeParameters);
        }
        List<ClassOrInterfaceType> extendz = n.getExtends();
        if (extendz != null) {
            for (int i = 0; i < extendz.size(); i++) {
                extendz.set(i, (ClassOrInterfaceType) extendz.get(i).accept(this, arg));
            }
            removeNulls(extendz);
        }
        List<ClassOrInterfaceType> implementz = n.getImplements();
        if (implementz != null) {
            for (int i = 0; i < implementz.size(); i++) {
                implementz.set(i, (ClassOrInterfaceType) implementz.get(i).accept(this, arg));
            }
            removeNulls(implementz);
        }
        List<BodyDeclaration> members = n.getMembers();
        if (members != null) {
            for (int i = 0; i < members.size(); i++) {
                members.set(i, (BodyDeclaration) members.get(i).accept(this, arg));
            }
            removeNulls(members);
        }
        return n;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜