以编程方式提取方法的内容



例如,如果我有一个example.java文件,如下所示

Class Example{
int a;
int b;
void helloworld(){
System.out.println("HelloWorld");
}
void hello(){
System.out.println("HelloWorld");
}

如何以编程方式将函数helloWorld((的内容作为字符串获取,如

void helloworld(){
System.out.println("HelloWorld");
}

我的意思是,它应该接受方法名称作为输入,并将其内容作为字符串返回??

由于方法体是字节码,因此无法获取。这个问题很久以前就被问过了,你可以在How do I print the method body reflectively找到答案?

您可以得到的最大值是方法签名,如下例所示。

import java.lang.reflect.Method;
public class reflectionexample {
public static void main(String[] args) {
try {
Class c = TestMe.class;
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
for (Method method : allMethods) {
System.out.println(method.toGenericString());
}
} catch (Exception e) {
e.printStackTrace();
} 
}
}

class TestMe {
void extractMePlease(String justLikeThat) {
System.out.println("is it working?");
}
}

输出

void compareInt.TestMe.extractMePlease(java.lang.String)

希望它能有所帮助!

最新更新