Demo4
使用反射机制调用方法
package reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;
public class ReflectDemo4 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Person p = new Person();
p.sayHello();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入类名:");
String className = scanner.nextLine();
System.out.println("请输入方法名:");
String methodName = scanner.nextLine();
//1。实例化
Class cls = Class.forName(className);//Class cls = Class.forName("reflect.Person");
Object obj = cls.newInstance();
//2.获取要调用的方法
Method method =cls.getMethod(methodName);//Method method = cls.getMethod("sayHello");
method.invoke(obj);//p.sayHello();
}
}
控制台结果展示:
Demo5
调用有参方法
(可借鉴Demo3获取有参构造器)
import java.lang.reflect.Method;
public class ReflectDemo5 {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("reflect.Person");
Object obj = cls.newInstance();
//say(String info)
Method m1 = cls.getMethod("say",String.class);
m1.invoke(obj,"你好");
//say(String info,int count)
Method m2 = cls.getMethod("say",String.class,int.class);
m2.invoke(obj,"呵呵",5);
}
}
Demo6
利用java反射机制调用目标类的私有方法
1)Class的方法: Method getMethod() Method[] getMethods() 上述两个方法只能用于获取Class所表示的类的公开方法(包含从超类继承的) 2)Method getDeclaredMethod() Method[] getDeclaredMethods() 上述两个方法可以获取Class所表示的类中自己定义的方法包含私有的,不包含从超类继承的
package reflect;
import java.lang.reflect.Method;
public class ReflectDemo6 {
public static void main(String[] args) throws Exception {
// Person p = new Person();
// p.heihei();//编译不通过
Class cls = Class.forName("reflect.Person");
Object obj = cls.newInstance();
Method method = cls.getDeclaredMethod("heihei");
method.setAccessible(true);//强行打开访问权限
method.invoke(obj);
}
}
控制台结果展示: