您的位置:首页 > 编程语言 > Java开发

java基础--反射(成员变量)

2013-10-09 20:14 549 查看
这里介绍通过反射获取对象的成员变量,以及修改成员变量。

package Reflect.field;

public class Point {

int y;

public int getY() {
return y;
}

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

public Point(int y) {
super();
this.y = y;
}

}


package Reflect.field;

public class ReflectPoint extends Point {

protected int x; // 必须要用public修饰 否则反射取不到

public int y; // 必须要用public修饰 否则反射取不到

public String str1 = "hello";
public String str2 = "world";
public String str3 = "OK";

public ReflectPoint(int x, int y) {

super(10);
this.x = x;
this.y = y;
}

// 覆盖了此方法,就可以直接System.out.println(new ReflectPoint());
@Override
public String toString() {
return str1 + ":" + str2 + ":" + str3;
}

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;
}

}


package Reflect.field;

import java.lang.reflect.Field;

/**
* 成员变量的反射
*
* @author xiaoyu
*
*/
public class Test {

public static void main(String[] args) throws Exception {

// 测试通过反射 获取对象的变量
ReflectPoint pt1 = new ReflectPoint(3, 5);
Point pt = new Point(99);

Field fieldY = pt1.getClass().getField("y"); // 这样只能取得public 修饰的y
Field allFieldY = pt.getClass().getDeclaredField("y"); // 这样所有的y,不管是什么修饰符

// fieldY不是对象上的变量,它是类上的。 fieldY.get(pt1)
System.out.println(fieldY.get(pt1)); // 5
System.out.println(allFieldY.get(pt)); // 99

Field fieldX = pt1.getClass().getDeclaredField("x");
// 暴力反射 ,不管x 是不是Public
// 修饰的,都可以取到(用了getDeclaredField("x"),setAccessible(true)可以不用写了)
// fieldX.setAccessible(true);
System.out.println(fieldX.get(pt1)); // 3

// 下面测试通过反射改变一个对象的变量的值
changeStringValue(pt1);
// 打印出pt1中的String类型的值
System.out.println(pt1);

}

/**
* 该方法可以改变对象obj中String类型的变量
*
* @param obj
*/
public static void changeStringValue(Object obj) throws Exception {
Field[] fileds = obj.getClass().getFields(); // 获取obj对象的所以变量
for (Field field : fileds) { // 循环找出是String类型的变量
// 字节码只有一份,所以可以==,而且比equals()方法更好
if (field.getType() == String.class) {// 如果是String类型的,则改变其值

String oldValue = (String) field.get(obj);
String newValue = oldValue.replace('o', 'h');
field.set(obj, newValue);// 当然你也可以设置成新的值 ;field.set(obj, "WWW");

}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java java基础
相关文章推荐