Java:解析java源代码,解压缩方法 [英] Java : parse java source code, extract methods

查看:128
本文介绍了Java:解析java源代码,解压缩方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望解析java源代码文件,并提取方法源代码。

I wish to parse java source code files, and extract the methods source code.

我需要这样的方法:

/** Returns a map with key = method name ; value = method source code */
Map<String,String> getMethods(File javaFile);

有没有一种简单的方法来实现这一点,一个库可以帮我构建我的方法等等?

Is there a simple way to achieve this, a library to help me build my method, etc. ?

推荐答案

http://javaparser.github.io/javaparser/

您必须编写一些代码。此代码将调用解析器...它将返回一个CompilationUnit:

You'll have to write some code. This code will invoke the parser... it will return you a CompilationUnit:

            InputStream in = null;
            CompilationUnit cu = null;
            try
            {
                    in = new SEDInputStream(filename);
                    cu = JavaParser.parse(in);
            }
            catch(ParseException x)
            {
                 // handle parse exceptions here.
            }
            finally
            {
                  in.close();
            }
            return cu;

注意:SEDInputStream是输入流的子类。如果需要,可以使用FileInputStream。

Note: SEDInputStream is a subclass of input stream. You can use a FileInputStream if you want.

您必须创建一个访问者。您的访问者很容易,因为您只对方法感兴趣:

You'll have to create a visitor. Your visitor will be easy because you're only interested in methods:

  public class MethodVisitor extends VoidVisitorAdapter
  {
        public void visit(MethodDeclaration n, Object arg)
        {
             // extract method information here.
             // put in to hashmap
        }
  }






要调用访问者,请执行以下操作:


To invoke the visitor, do this:

  MethodVisitor visitor = new MethodVisitor();
  visitor.visit(cu, null);

这篇关于Java:解析java源代码,解压缩方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆