本文共 1928 字,大约阅读时间需要 6 分钟。
1.1.1 反射获取普通成员方法
反射public方法执行流程package com.itheima_01;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*
通过反射获取成员方法并使用
Method getMethod(String name, Class<?>... parameterTypes)
Method:
Object invoke(Object obj, Object... args)
*/
public class ReflectDemo5 {
public static void main(String[] args) throws ReflectiveOperationException {
//获取学生类的字节码对象
Class clazz = Class.forName("com.itheima_01.Student");
//获取学生类的对象
Object stu = clazz.newInstance();
//获取无参有返回值的方法
Method m = clazz.getMethod("getName");
Object obj = m.invoke(stu);
System.out.println(obj);
}
private static void method2(Class clazz, Object stu)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//获取有参无返回值的方法
Method m = clazz.getMethod("setName", String.class);
m.invoke(stu, "lisi");
System.out.println(stu);
}
private static void method(Class clazz, Object stu)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//获取无参无返回值的方法
Method m = clazz.getMethod("method");
m.invoke(stu);
}
}
1.1.3 方法总结Class: Method getMethod(String name, Class ... parameterTypes) // 此方法由字节码对象调用 // 参数1: 要反射的方法名称 // 参数2: 此方法需要接受的参数类型(注意,传入的都是字节码)Method: Object invoke(Object obj, Object... args) // 方法由Method对象调用 // 参数1: 要由那个对象调用方法 // 参数2: 方法需要的具体实参(实际参数)1.1.4 问题: 私有的成员方法怎么玩? // 获取字节码对象 Class clazz = Class.forName("com.heima.Student"); // 创建学生对象 Object stu = clazz.newInstance(); // 暴力反射获取方法 Method method = clazz.getDeclaredMethod("method"); // 让jvm不检查权限 method.setAccessible(true); // 执行方法 method.invoke(stu);
转载于:https://blog.51cto.com/13587708/2373052