|
@@ -1,11 +1,53 @@
|
|
|
package homework0813;
|
|
package homework0813;
|
|
|
|
|
|
|
|
|
|
+import java.lang.reflect.Method;
|
|
|
|
|
+import java.util.Arrays;
|
|
|
|
|
+import java.util.stream.Collectors;
|
|
|
|
|
+
|
|
|
/**
|
|
/**
|
|
|
|
|
+ * @author WanJl
|
|
|
|
|
+ * @version 1.0
|
|
|
* @title MethodPrivateTest
|
|
* @title MethodPrivateTest
|
|
|
- * @description
|
|
|
|
|
- * @author WanJl
|
|
|
|
|
- * @version 1.0
|
|
|
|
|
- * @create 2026/8/14
|
|
|
|
|
|
|
+ * @description
|
|
|
|
|
+ * @create 2026/8/14
|
|
|
*/
|
|
*/
|
|
|
public class MethodPrivateTest {
|
|
public class MethodPrivateTest {
|
|
|
-}
|
|
|
|
|
|
|
+ public static void main(String[] args) throws Exception {
|
|
|
|
|
+ // 1. 创建 Student 对象,反射调用 setName("张三")(复用练习六工具)
|
|
|
|
|
+ Student student=new Student(101,"张三",25,"男","zhangsan@qq.com","13636363366");
|
|
|
|
|
+ // 2. 暴力反射调用私有实例方法 read()(invoke 传对象 s)
|
|
|
|
|
+
|
|
|
|
|
+ // 3. 暴力反射调用私有静态方法 write()(invoke 传 null)
|
|
|
|
|
+ // 4. 用封装好的 invokeAnyMethod 工具调用 read(obj 传 s)/ write(obj 传 null)
|
|
|
|
|
+ invokeAnyMethod(student,"read");
|
|
|
|
|
+ invokeAnyMethod(student.getClass(),"write");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // 通用工具:反射调用任意权限方法(getDeclaredMethod + setAccessible + invoke)
|
|
|
|
|
+ public static Object invokeAnyMethod(Object obj, String methodName, Object... args) throws Exception {
|
|
|
|
|
+ // 1. 计算参数类型数组
|
|
|
|
|
+ Class<?>[] argsClasses=new Class[args.length];
|
|
|
|
|
+ for (int i = 0; i < args.length; i++) {
|
|
|
|
|
+ argsClasses[i]=args[i].getClass();
|
|
|
|
|
+ }
|
|
|
|
|
+ //判断,obj到底是什么类型,如果obj属于Class类型,无论是那个类的Class对象,都会进入到if语句中
|
|
|
|
|
+ if (obj instanceof Class<?>){
|
|
|
|
|
+ //强转,把obj转换成Class类型
|
|
|
|
|
+ Class<?> clazz =(Class<?>)obj;
|
|
|
|
|
+ // 2. getDeclaredMethod(methodName, 参数类型...) 获取方法(含 private)
|
|
|
|
|
+ Method method = clazz.getDeclaredMethod(methodName, argsClasses);
|
|
|
|
|
+ // 3. setAccessible(true) 暴力反射放开权限
|
|
|
|
|
+ method.setAccessible(true);
|
|
|
|
|
+ // 4. invoke(obj, args) 调用并返回结果
|
|
|
|
|
+ return method.invoke(null,args);
|
|
|
|
|
+ }
|
|
|
|
|
+ //如果obj不是Class类型,说明传入进来的是其他的对象,要调用的也是其他的实例方法,而不是静态方法
|
|
|
|
|
+ Class<?> clazz=obj.getClass();
|
|
|
|
|
+ // 2. getDeclaredMethod(methodName, 参数类型...) 获取方法(含 private)
|
|
|
|
|
+ Method method = clazz.getDeclaredMethod(methodName, argsClasses);
|
|
|
|
|
+ // 3. setAccessible(true) 暴力反射放开权限
|
|
|
|
|
+ method.setAccessible(true);
|
|
|
|
|
+ // 4. invoke(obj, args) 调用并返回结果
|
|
|
|
|
+ return method.invoke(obj,args);
|
|
|
|
|
+ }
|
|
|
|
|
+}
|