不太明白你的意思,发点我之前写的练习题给你,或许对你有帮助
使用内省一个JavaBean的成员写入与读取方法
//创建内省对象
IntroSpector iSpector = new IntroSpector();
new PropertyDescriptor("num",IntroSpector.class).getWriteMethod().invoke(iSpector, 1232);
System.out.println(iSpector.getNum());
Object numObject =
new PropertyDescriptor("num", iSpector.getClass()).getReadMethod().invoke(iSpector, null);
System.out.println(numObject);
使用反射改变对象中所有参数中包含的数字
package com.heima.test;
import java.lang.reflect.*;
public class Main {
public static void main(String[] args)throws Exception{
//得到类的字节码类
Class cls = ReflectPoint.class;
//以类名方式得到字节码类
Class clsArgs = Class.forName("com.heima.test.ReflectPoint");
//获取该类的带参构造方法
Constructor constructor1 = clsArgs.getConstructor(int.class,int.class,int.class,int.class,int.class);
//获取该类的无参数构造方法
Constructor constructor2 = clsArgs.getConstructor();
//通过反射创建一个无参实例
ReflectPoint rPoint = (ReflectPoint)constructor2.newInstance();
//单句反射创建一个有参实例
ReflectPoint onePoint = (ReflectPoint)Class.forName("com.heima.test.ReflectPoint")
.getConstructor(int.class,int.class,int.class,int.class,int.class).newInstance(551, 231, 425, 435, 576);
//打印
System.out.println(onePoint.toString());
//获取参数对象
Field[] fields = cls.getDeclaredFields();
//迭代
for (Field field : fields) {
//符合int型
if (field.getType() == int.class) {
//将每个参数的值以string形势取出
String str = field.get(onePoint).toString();
//替换其中的内容
str = str.replace('5', '9');
//将字符串转为Integer
Integer num = Integer.valueOf(str);
//将新数据设置回对应对象的变量中
field.set(onePoint, num);
}
}
//打印
System.out.println(onePoint.toString());
}
} |