如何使用反射调用java中的方法 [英] How to invoke a method in java using reflection
本文介绍了如何使用反射调用java中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用反射调用带参数的方法?
How can I invoke a method with parameters using reflection ?
我想指定这些参数的值.
I want to specify the values of those parameters.
推荐答案
这是一个使用涉及原语的反射调用方法的简单示例.
Here's a simple example of invoking a method using reflection involving primitives.
import java.lang.reflect.*;
public class ReflectionExample {
public int test(int i) {
return i + 1;
}
public static void main(String args[]) throws Exception {
Method testMethod = ReflectionExample.class.getMethod("test", int.class);
int result = (Integer) testMethod.invoke(new ReflectionExample(), 100);
System.out.println(result); // 101
}
}
为了健壮,您应该捕获并处理所有已检查的反射相关异常NoSuchMethodException
、IllegalAccessException
、InvocationTargetException
.
To be robust, you should catch and handle all checked reflection-related exceptions NoSuchMethodException
, IllegalAccessException
, InvocationTargetException
.
这篇关于如何使用反射调用java中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文