反射改变变量值
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