java中常用的反射

java中常用的反射

public class User {

    private String name;
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

1、根据属性名称,利用反射射设置private属性的值

    //根据属性名称,利用反射射设置private属性的值
    public static void setPrivateValue(User user, String privateName, String privateValue) {
        try {
            Field privateStringField = user.getClass().getDeclaredField(privateName);
            privateStringField.setAccessible(true);
            privateStringField.set(user, privateValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        User user = new User();
        setPrivateValue(user, "name", "hellworld");
         System.out.println(user.getName());//输出 hellworld

2、获取根据函数名调用函数,无参数

   //获取根据函数名调用函数,无参数
    public static Object callingMethod(User user, String methodName) {
        try {
            Method method = user.getClass().getDeclaredMethod(methodName);
            return method.invoke(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
  User user = new User();
  setPrivateValue(user, "name", "hellworld");
   System.out.println(callingMethod(user, "getName"));//输出 hellworld

3、获取根据函数名调用函数,带参数

  //获取根据函数名调用函数,有参数
    public static Object callingMethod(User user, String methodName, Class<?>[] cls, Object[] objs) {
        try {
            Method method = user.getClass().getDeclaredMethod(methodName, cls);
            return method.invoke(user, objs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    User user = new User();
    callingMethod(user, "setName", new Class[]{String.class}, new Object[]{"hellowrld"});
     System.out.println(callingMethod(user, "getName"));//输出 hellworld
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值