Parse Attributes from Java Files using Java Parser

别等时光非礼了梦想. 提交于 2019-12-11 03:12:51

问题


I have 3 classes below.

public class A {
     B b;
}

public class B {
    C c;

    public C getC() {
        A a;
        return c;
    }
}

public class C {

}

I want to parse the classes using java parser having following info:

  • Class names
  • Method names
  • Attribute names

回答1:


I suggest you to start from the most recent version of JavaParser available on GitHub: https://github.com/javaparser/javaparser

You can easily create a project using Maven and including among the dependencies JavaParser:

  <dependency>
      <groupId>com.github.javaparser</groupId>
      <artifactId>javaparser-core</artifactId>
      <version>2.2.1</version>
  </dependency>

Then to parse a file is very easy:

 File sourceFile = new File("path/to/my/file.java");
 CompilationUnit compilationUnit = JavaParser.parse(sourceFile);

JavaParser returns the root node of the Abstract Syntax Tree which is a CompilationUnit and represents all the contents of a file. You just need to navigate this tree and extract the information.

For example from a CompilationUnit you can get the top types (but not the internal classes) using the method getTypes which will return a list of TypeDeclaration. A TypeDeclaration can be either a class, an interface or an enum. TypeDeclaration has the method getName that you can use to get the name of the declared type. You could then ask the members of a TypeDeclaration and look for internal classes, methods or fields.

Other two ways to navigate the tree are: * using visitors * using the method getChildrenNodes which is available on every node (CompilationUnit, TypeDeclaration, methods declarations, statements etc.)

To use the visitor pattern check the package visitor in JavaParser: there are already several abstract visitors to extend. Once you have created your visitor you can just invoke it using compilationUnit.accept(myVisitor, <extra arg>); and it will crawl the whole tree.

If you want to use the getChildrenNodes instead you can do something along these lines:

void processNode(Node node) {
   if (node instanceof TypeDeclaration) {
      // do something with this type declaration
   } else if (node instanceof MethodDeclaration) {
      // do something with this method declaration
   } else if (node instanceof FieldDeclaration) {
      // do something with this field declaration
   }
   for (Node child : node.getChildrenNodes()){
      processNode(child);
   }
}

...
CompilationUnit cu = JavaParser.parse(sourceFile);
processNode(node);
...

Hope it helps and if you have other questions specific to JavaParser feel free to open an issue or join the JavaParser chat.

Disclaimer: I am a contributor of the JavaParser project



来源:https://stackoverflow.com/questions/32178349/parse-attributes-from-java-files-using-java-parser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!