java反射之成员变量的反射
程序员文章站
2024-01-25 19:48:34
...
public class ReflectTest {
public static void main(String[] args) throws Exception {
//成员变量的反射
ReflectPoint pt1 = new ReflectPoint(3, 5);
Field fieldY = pt1.getClass().getField("y");
System.out.println(fieldY.get(pt1));//5 因为y是公有属性,可以直接得到
Field fieldX = pt1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1));//3 x是私有属性,使用getDeclaredField,然后setAcces sible(true)
changeStringValue(pt1);
System.out.println(pt1);//aall:aasketaall:itcast
}
private static void changeStringValue(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for(Field field :fields){
if(field.getType()==String.class){
String oldValue = (String) field.get(obj);
String newValue = oldValue.replace('b', 'a');
field.set(obj, newValue);
}
}
}
}
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString(){
return str1+":"+str2+":"+str3;
}
}
转载于:https://my.oschina.net/projerry/blog/515637
上一篇: 成员变量的反射
下一篇: java反射的应用 构造方法 成员变量