简体   繁体   English

如何从.java文件中获取方法列表

[英]how to get list of methods from .java file

I have a path of a .java file in my Java program. 我的Java程序中有一个.java文件的路径。 I want to get the list of methods that are available in the .java file. 我想获取.java文件中可用的方法列表。

For example, I have a .java file at 'C:\\temp\\Foo.java' as follows: 例如,我在'C:\\ temp \\ Foo.java'中有一个.java文件,如下所示:

class Foo{
    public int add(int a, int b){ return a+b;}
    public int sub(int a, int b){ return a-b;}
}

In my program, I want to get the method names add and sub . 在我的程序中,我想获取方法名称addsub Is there any java api to achieve the same? 是否有任何java api实现相同? I know that for .class file, we can achieve it using Reflection, but is it possible for .java file? 我知道对于.class文件,我们可以使用Reflection实现它,但是.java文件可能吗?

You can use javaparser library. 您可以使用javaparser库。

Here is sample code from their wiki page: 以下是其Wiki页面中的示例代码:

public class MethodPrinter {

    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("test.java");

        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }

        // visit and print the methods names
        new MethodVisitor().visit(cu, null);
    }

    /**
     * Simple visitor implementation for visiting MethodDeclaration nodes. 
     */
    private static class MethodVisitor extends VoidVisitorAdapter {

        @Override
        public void visit(MethodDeclaration n, Object arg) {
            // here you can access the attributes of the method.
            // this method will be called for all methods in this 
            // CompilationUnit, including inner class methods
            System.out.println(n.getName());
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM