反射——反射爆破操作方法

通过反射访问类中成员

  1. 根据方法名和参数列表获取 Method 方法对象:Method m = clazz.getDeclaredMethod(方法名, XX.class);
  2. 获取对象:Object o=clazz.newlnstance();
  3. 暴破:m.setAccessible(true);
  4. 访问:Object returnValue = m.invoke(o,实参列表);
  5. 注意:如果是静态方法,则 invoke 的参数 o ,可以写成 null


package reflection_;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: Gin
 * @Description:
 * @Modified By: Gin
 * @Date: Created in 10:10 2021/9/30
 */
public class ReflectAccessMethod {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException {

        // 1. 得到 Boss 类对应的 Class 对象
        Class<?> boosCls = Class.forName("reflection_.Boss");
        // 2. 创建对象
        Object o = boosCls.newInstance();
        // 3. 调用 public 的 hi 方法
        // Method hi = boosCls.getMethod("hi", String.class); // getMethod():获取 public 的方法
        // 3.1 得到 hi 方法对象
        Method hi = boosCls.getDeclaredMethod("hi", String.class); // getDeclaredMethod():获取任意方法
        // 3.2 调用
        hi.invoke(o, "Gin Sherry");

        // 4. 调用 private static 方法
        // 4.1 得到 say 方法对象
        Method say = boosCls.getDeclaredMethod("say", int.class, String.class, char.class);
        // 4.2 IllegalAccessException 因为 say 方法是私有的,所以需要爆破
        say.setAccessible(true);
        System.out.println(say.invoke(o, 356, "Gin", 'A'));
        // 4.3 因为 say 方法是 static 的,所以 o 可以写成 null
        System.out.println(say.invoke(null, 356, "Vodka", 'B'));

        // 5. 在反射中,如果方法有返回值,则统一返回 Object
        Object reVal = say.invoke(null, 4869, "Vermouth", 'S');
        System.out.println("reVal 的运行类型 " + reVal.getClass());

    }
}
class Boss{ // 类
    private static String name;
    public int age;

    public Boss() { // 构造器
    }

    private static String say(int n, String s, char c){ // 静态私有方法
        return n + " " + s + " " + c;
    }

    public void hi(String s){ // 普通公有方法
        System.out.println("hi" + s);
    }

}


在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值