我正在解析
Java源文件以收集有关我的类的各种信息.因此我使用
JavaParser,因为我找不到一个好的选择(好的建议有机会成为“答案”)来解析源文件.
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:" + ((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() + "\""); } } } } } } }
现在我如何获得类本身的注释?
解决方法
您正在覆盖访问方法的公共无效访问(MethodDeclaration n,Object arg).您还可以覆盖public void visit(ClassOrInterfaceDeclaration n,A arg)或public void visit(ClassOrInterfaceType n,A arg),它可以让您访问您要查找的信息.