【问题标题】:JavaScript: Parse Java source code, extract methodJavaScript:解析Java源代码,提取方法
【发布时间】:2017-10-25 00:32:50
【问题描述】:

我正在尝试构建一个使用 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: [] }

其中方法将由 types 中的“MethodDeclaration”标识。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript java node.js babeljs abstract-syntax-tree


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2015-01-22
      • 1970-01-01
      • 2014-07-13
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多