Java中通过反射调用类中的方法,具体实现起来要注意两点:
(1)通过 Class 类的 getMethod 方法取的 Method 对象,并设置调用方法时需要的参数类型。
(2)使用 Method 方法调用 invoke 方法,并向该方法传递参数,其参数通常是一个类的对象。
个人总结,大致需要以下四个步骤:
1. 获取当前类的Class对象。? ? ? ? ? ? ? (通过forName()动态加载类)
2. 实例化这个Class对象。? ? ? ? ? ? ? ? (通过newInstance:? Object obj=student.newInstance() )
3. 获取当前类的某个(些)方法
4用? 方法对象名.invoke ,通过Class对象的实例,调用带相应参数的,当前类的方法。
代码如下:
******************学生类****************
类里面有两个方法,一个带参数,一个不带参数
package zj4_6;
import java.lang.reflect.InvocationTargetException;
public class Student {
? ? public void printInfo(){
? ? ? ? System.out.println("打印学生信息");
? ? }
? ? public void printAddress(String address){
? ? ? ? System.out.println("hellow,I come from "+address);
? ? ? ?
? ? }
}
***********************主函数类***************************
调用Student类中的两个方法
package zj4_6;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeMethod1 {
? ? /**
? ? * 通过反射,调用类中的方法
? ? * @throws SecurityException
? ? * @throws NoSuchMethodException
? ? * @throws InstantiationException
? ? * @throws InvocationTargetException
? ? * @throws IllegalArgumentException
? ? * @throws IllegalAccessException
? ? */
? ? public static void main(String[] args) throws Exception {
? ? ? ? try {
? ? ? ? ? ? Class student=Class.forName("zj4_6.Student");//动态加载类,获取当前类的Class对象
? ? ? ? ? ? //获取Student类名称为printinfo地方法
? ? ? ? ? ? Method methods1=student.getMethod("printInfo");
? ? ? ? ? ? //调用frintInfo方法
? ? ? ? ? ? methods1.invoke(student.newInstance()); //通过实例化的对象,调用无参数的方法
? ? ? ? ? ? //获取类中名称为printInfo地方法,String,class是参数类型
? ? ? ? ? ? Method methods2=student.getMethod("printAddress", String.class);//注意参数不是String
? ? ? ? ? ? //调用printAddress方法,其中HK是方法传入的参数值
? ? ? ? ? ? methods2.invoke(student.newInstance(),"HK");//通过对象,调用有参数的方法
} catch (ClassNotFoundException e) { 29? e.printStackTrace(); 30? } 31? } 32 }
运行结果如下:
