成员变量的反射实例
程序员文章站
2024-01-25 19:48:34
...
package com.demo.day01;
import java.lang.reflect.Field;
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 ="itcast";
@Override
public String toString() {
return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
+ str3 + "]";
}
public static void main(String[] args) throws Exception {
ReflectPoint rp1 = new ReflectPoint();
changeStringValue(rp1);
}
private static void changeStringValue(Object obj) throws IllegalArgumentException, IllegalAccessException {
//obj.getClass():获得字节码
//.getFields():获得所有字段
//此时fields中只有四个字节码对象,(x是私有属性)
Field[] fields = obj.getClass().getFields();
for(Field field:fields){
//获取字段类型(属性类型)比较类型用==
if(field.getType() == String.class){
String oldVal = (String) field.get(obj);
String newValue = oldVal.replace("b", "a");
field.set(obj, newValue);
}
}
}
}
上一篇: Ajax Java异步请求返回实体类