[英]how to get list of methods from .java file
我的Java程序中有一个.java
文件的路径。 我想获取.java
文件中可用的方法列表。
例如,我在'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;}
}
在我的程序中,我想获取方法名称add
和sub
。 是否有任何java api实现相同? 我知道对于.class
文件,我们可以使用Reflection实现它,但是.java
文件可能吗?
您可以使用javaparser库。
以下是其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.