我使用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字符?爲什麼這會是有用的功能?如果屬實的話很有趣。 –