Java脚本:解析Java源代码,提取方法

JavaScript: Parse Java source code, extract method

我正在尝试使用 nodeJs 构建一个 returns 给定 Java 源代码的所有方法的模块。到目前为止,我可以获得使用 "java-parser" 模块构建的 AST 树,但我需要遍历它以过滤掉方法。

 code = ' public class CallingMethodsInSameClass
 {
    public static void main(String[] args) {
        printOne();
        printOne();
        printTwo();
 }
 public static void printOne() {
    System.out.println("Hello World");
 }

 public static void printTwo() {
    printOne();
    printOne();
} }';

var javaParser = require("java-parser");
var traverse = require("babel-traverse").default;
var methodsList = [];
traverse(ast, {
  enter(path){
  //do extraction
  }
}

我知道 babel-traverse 是为 Js 设计的,但我想要一种遍历的方法,这样我就可以过滤方法。 我收到此错误

throw new Error(messages.get("traverseNeedsParent", parent.type));
  ^

 Error: You must pass a scope and parentPath unless traversing a 
 Program/File. Instead of that you tried to traverse a undefined node 
 without passing scope and parentPath.

如果记录的 AST 看起来像

{ node: 'CompilationUnit',
  types: 
   [ { node: 'TypeDeclaration',
       name: [Object],
       superInterfaceTypes: [],
       superclassType: null,
       bodyDeclarations: [Array],
       typeParameters: [],
       interface: false,
       modifiers: [Array] } ],
  package: null,
  imports: [] }

其中方法将由 "MethodDeclaration" 在 类型 中标识。感谢任何帮助。

AST 只是另一个 JSON 对象。试试 jsonpath.

npm install jsonpath

要提取所有方法,只需按条件过滤 node=="MethodDeclaration":

var jp = require('jsonpath');
var methods = jp.query(ast, '$.types..[?(@.node=="MethodDeclaration")]');
console.log(methods);

有关更多 JSON 路径语法,请参阅 here