如何使用reflection在java中调用方法
如何使用reflection调用带参数的方法?
我想指定这些参数的值。
这是一个使用涉及基元的reflection调用方法的简单示例。
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 } }
为了健壮,您应该捕获并处理所有已检查的与reflection相关的exceptionNoSuchMethodException
, IllegalAccessException
, InvocationTargetException
。
使用reflection调用类方法非常简单。 您需要在其中创建一个类并生成方法。 如下。
package reflectionpackage; public class My { public My() { } public void myReflectionMethod() { System.out.println("My Reflection Method called"); } }
并使用reflection在另一个类中调用此方法。
package reflectionpackage; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectionClass { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class c=Class.forName("reflectionpackage.My"); Method m=c.getDeclaredMethod("myReflectionMethod"); Object t = c.newInstance(); Object o= m.invoke(t); } }
在此查找更多详情 。
您可以在任何Object中使用getClass来发现它的类。 然后,您可以使用getMethods来发现所有可用的方法。 一旦有了正确的方法,就可以使用任意数量的参数调用invoke
这是我所知道的最简单的方法,它需要被try&catch包围:
方法m = .class.getDeclaredMethod(“”,arg_1.class,arg_2.class,… arg_n.class); result =()m.invoke(null,(Object)arg_1,(Object)arg_2 …(Object)arg_n);
这是用于调用静态方法,如果要调用非静态方法,则需要将m.invoke()的第一个参数从null替换为调用基础方法的对象。
不要忘记向java.lang.reflect添加导入。*;