例如,如果我有一个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");
}
我的意思是它应该接受方法名称作为输入并以字符串形式返回其内容?
答案 0 :(得分:0)
因为它是字节码,所以无法获得方法主体。这个问题很早以前就被问到了,您可以在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)
希望有帮助!