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

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

我正在尝试构建一个模块,该模块使用 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/

相关文章:

asp.net - 我的 javascript 代码在 mozilla firefox 中不起作用

javascript - 创建大型 Nodejs 缓存

javascript - 修复 html 表格的表头在顶部

java - 在java程序中修改图形?

java - 工厂模式用于实例化单个类的复杂对象

java - RxJava2 组合多个可观察量以使它们返回单个结果

javascript - NodeJS x-ray web-scraper : how to follow links and get content from sub page

node.js - Webtask + Sendgrid = 编译失败?

javascript - 如何在钛工作室的每一行放置一个按钮?

javascript - window.open 有时会打开链接,有时不会