我使用https://github.com/javaparser/javaparser来解析Java源代码
我尝试了很多方法来解析内部类;像这样:
class A {
int x;
public void method2() {...}
class B {
int number;
public void methods() {...}
}
}
我尝试解析类B及其变量和方法,但失败了。
有没有例子说明如何获得B类?
我可以解析A类方法的名称和内容或变量内容,如下所示:
CompilationUnit cu = JavaParser.parse(in);
ClassVisitor classVisitor = new ClassVisitor();
classVisitor.visit(cu, null);
class ClassVisitor extends VoidVisitorAdapter<Void> {
@Override
public void visit(ClassOrInterfaceDeclaration n, Void arg) {
System.out.println(n.getFields());
// get class methods
for(MethodDeclaration method : n.getMethods()) {
System.out.println("Name :" + method.getName());
System.out.println("Body :" + method.getBody().get());
}
}
}
}
但是我尝试解析B类变量和方法,失败了!
尝试像这样的CompilationUnit.getTypes():
CompilationUnit cu = JavaParser.parse(in);
for(TypeDeclaration<?> type : cu.getTypes()) {
log.info("Type Name :{}", type.getName());
}
结果: n.s.dictionary.parse.JavaCodeParse:类型名称:A
不属于B类
答案 0 :(得分:1)
对于需要它的人:
for(TypeDeclaration type : cu.getTypes()) {
// first give all this java doc member
List<BodyDeclaration> members = type.getMembers();
// check all member content
for(BodyDeclaration member : members) {
// if member state equal ClassOrInterfaceDeclaration, and you can identify it which is inner class
if(member.isClassOrInterfaceDeclaration()) {
log.info("class name :{}", member.asClassOrInterfaceDeclaration().getName());
// get inner class method
for(MethodDeclaration method : member.asClassOrInterfaceDeclaration().getMethods()) {
log.info("Method Name :{}", method.getName());
}
VerifyInnerClassAndParse(member.asClassOrInterfaceDeclaration());
}
}
}
如果您有许多内部类,只需编写递归方法
答案 1 :(得分:0)
不需要递归,只需在访问者方法中调用super.visit(n,arg)。