[英]Calling a method in Java using reflection, and obtaining the return value
I want to call a method using reflection. 我想使用反射调用方法。
The method is: 方法是:
public String format(String text,int value)
{
return text+" "+value;
}
So, it has 2 arguments: a String and an int. 因此,它有2个参数:一个String和一个int。 And it returns a String.
它返回一个字符串。 How can I call it?
我怎么称呼它?
try {
Class<?> type = Foo.class;
Method method = type.getMethod("format", String.class, int.class);
//as the method is not static, you need to have an instance of the class to be able to invoke the method
Foo instance = new Foo();
String string = (String) method.invoke(instance, "string", 42);
} catch (Exception toBeHandled) {}
and replace the Foo
with the name of your class 并用您的班级名称替换
Foo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.