反射获取方法并调用。说再多不入代码来的快。我把代码分成了一块块代码区,需要看一个注释其他的就可以了,测试过都是可以的!
package FanShe;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Student3 {
//**************成员方法***************//
public void show1(String s){
System.out.println("调用了:公有的,String参数的show1(): s = " + s);
}
protected void show2(){
System.out.println("调用了:受保护的,无参的show2()");
}
void show3(){
System.out.println("调用了:默认的,无参的show3()");
}
private String show4(int age){
System.out.println("调用了,私有的,并且有返回值的,int参数的show4(): age = " + age);
return "abcd";
}
}
public class MethodDemo {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
Class c=Student3.class;
/*//父类与自身都获取public
Method[] m=c.getMethods();
for(Method me:m) {
System.out.println(me);
}*/
//自身全都获取
/*Method[] m=c.getDeclaredMethods();
for(Method me:m) {
System.out.println(me);
}*/
//获取自身的指定public方法
/* Method m=c.getMethod("show1", String.class);
System.out.println(m);
//
Object obj = c.newInstance();
m.invoke(obj, "傅");*/
// //任意方法获取与调用
Method f=c.getDeclaredMethod("show4", int.class);
System.out.println(f);
f.setAccessible(true);
Object obj=c.newInstance();
f.invoke(obj, 838768967);
}
}