我使用Eclipse JDT库解析java源代码以访问在类中定义的所有方法。当代码在方法主体中包含注释“// xxxx”时,解析器将在注释之前停止,并且main(String [] args)方法被忽略。使用Eclipse JDT解析java文件
这是为解析所述样品的情况下:
public class HelloWorld {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
//Set the age
this.age = age;
System.out.println();
}
public static void main(String[] args) {
HelloWorld hw = new HelloWorld();
if(true) {
hw.setAge(10);
}
}
}
这是我写来解析上述样品的情况下的代码:当我使用它来解析代码
public class Parser {
/**
* Parse java program in given file path
* @param filePath
*/
public void parseFile(String filePath) {
System.out.println("Starting to parse " + filePath);
char[] source = readCharFromFile(filePath);
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(source);
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
return true;
}
@Override
public void endVisit(MethodDeclaration node) {
System.out.println("Method " + node.getName().getFullyQualifiedName() + " is visited");
}
});
}
}
,它可以仅得到getName()
,setName()
,getAge()
和getAge()
已被访问的结果,而main()
被忽略。
期待您的回答。谢谢。
它确实带\ n字符?为什么这会是有用的功能?如果属实的话很有趣。 –