我正在尝试构建一个模块,该模块使用 nodeJs 返回给定 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);
参见here了解更多 JSON 路径语法。
关于JavaScript:解析Java源代码,提取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922064/