反射认识_04_反射调用类方法Method
包1:
package ReflectionMethod;
public class ReflectionMethod {
String str1="str1";
public void outStr1(){
System.out.println("输出第一个字符串:"+str1);
}
public void outStr2(String str2){
System.out.println("输出第二个字符串:"+str2);
}
public void outStr3(String str3,String str4){
System.out.println("输出第三个字符串:"+str3);
System.out.println("输出第四个字符串:"+str4);
}
}
包2:
package ReflectionMethod;
import java.lang.reflect.Method;
public class ReflectionAchieve {
public static void main(String[] args) throws Exception {
ReflectionMethod rp=new ReflectionMethod();
useMethod(rp);
}
public static void useMethod(Object obj) throws Exception{
/*调用方法1,不带参数*/
Method out1=obj.getClass().getMethod("outStr1");//通过对象获得类,通过类获得类方法
out1.invoke(obj);//传入对象,并使用方法,如果是静态方法,可以传入null
/*调用方法2,带1个参数*/
Method out2=obj.getClass().getMethod("outStr2",String.class);//通过对象获得类,传入方法参数类型,通过类获得类方法
out2.invoke(obj,"str2");//传入对象,传入变量,并使用方法
/*调用方法3,带多个参数*/
Method out3=obj.getClass().getMethod("outStr3",String.class,String.class);//通过对象获得类,传入多个参数类型,通过类获得类方法
out3.invoke(obj,"str3","str4");//传入对象,传入多个变量,-使用方法
}
}
浙公网安备 33010602011771号