1、被测试的类
package cn.sunft.day01.reflect;
/**
* 定义一个点的类,供反射测试用
* @author sunft
*
*/
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;
}
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;
}
@Override
public String toString() {
return str1 + ":" + str2 + ":" + str3;
}
}
测试类中的代码:
package cn.sunft.day01.reflect;
import java.lang.reflect.Field;
/**
* 测试反射中的Field
* @author sunft
*
*/
public class FieldTest {
public static void main(String[] args) throws Exception {
ReflectPoint pt1 = new ReflectPoint(3, 5);
//这种方式只能获取public修饰的属性
Field fieldY = pt1.getClass().getField("y");
//fieldY的值是多少?是5,错!fieldY不是对象身上的变量,
//而是类上,要用它去取某个对象上对应的值
System.out.println(fieldY.get(pt1));
//私有的属性
Field fieldX = pt1.getClass().getDeclaredField("x");
fieldX.setAccessible(true);//设置访问为true
System.out.println(fieldX.get(pt1));
//修改值
changeStringValue(pt1);
//打印新的值
System.out.println(pt1);
}
/**
* 将对象中所有的类型为字符串的属性中的所有b字母替换成a
* @param obj
* @throws Exception
*/
private static void changeStringValue(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for(Field field : fields) {
//if(field.getType().equals(String.class)) {
//字节码在内存中只有一份,因此可以使用==比较;
//只要比较字节码,都只需要使用==比较即可
if(field.getType() == String.class) {
String oldValue = (String)field.get(obj);
//将旧值中所有的b替换成a
String newValue = oldValue.replace('b', 'a');
//给obj对象的field对象设置newValue的值
field.set(obj, newValue);
}
}
}
}
控制台打印的结果:
5
3
aall:aasketaall:itcast