java面试笔试知识点

反射改变变量值

package com.drj.demo.reflection;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * 
 * @ClassName: Demo
 * @Description:TODO(反射改变变量值)
 * @author: drj
 * @date: 2019年4月24日 下午8:59:30
 * 
 * @Copyright: 2019
 *
 */
public class Demo {
    public static void main(String[] args)
            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        ReflectPointer rp1 = new ReflectPointer(3, 4);
        Field fieldx = rp1.getClass().getField("x");// 必须是x或者y
        System.out.println("x=" + fieldx.get(rp1));
        Field[] filed = rp1.getClass().getDeclaredFields();
        for (Field f : filed) {
            if (f.getType().equals(String.class)) {
                System.out.println("变量名称" + f.getName() + "变量值" + f.get(rp1));
                String newVa = f.get(rp1).toString().replace("d", "x");
                f.set(rp1, newVa);
                System.out.println("修改后的值" + f.get(rp1).toString());
            }
            if (f.getType().equals(BigDecimal.class)) {
                f.setAccessible(true);// 暴力反射 可以將私有变量的值改变
                System.out.println("变量名称" + f.getName() + "变量值" + f.get(rp1));
            }
        }
    }
}

class ReflectPointer {

    public int x = 0;
    private int y = 0;
    public String name = "dair";
    private BigDecimal pass = new BigDecimal("666");

    public ReflectPointer(int x, int y) {// alt + shift +s相当于右键source
        super();
        // TODO Auto-generated constructor stub
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public String getName() {
        return name;
    }

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

    public BigDecimal getPass() {
        return pass;
    }

    public void setPass(BigDecimal pass) {
        this.pass = pass;
    }

}

测试结果

x=3
变量名称name变量值dair
修改后的值xair
变量名称pass变量值666

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蜗牛乌龟一起走

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值