黑马程序员技术交流社区
标题:
反射的有关问题
[打印本页]
作者:
ccyznhy
时间:
2013-8-23 10:23
标题:
反射的有关问题
本帖最后由 黄兴旺 于 2013-8-26 18:46 编辑
public class ReflectionPoint {
private int x;//对于私有的x怎么通过反射进行赋值
public int y;//对于公有的y怎么通过反射进行赋值,更简便。。。
String str1="abc";
String str2="ababb";
String str3="back";
private ReflectionPoint(int x,int y){
this.x=x;
this.y=y;
}
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;
}
}
作者:
xuluheng718
时间:
2013-8-23 13:25
ReflectionPoint point = new ReflectionPoint();
//得到ReflectionPoint的对象point的字节码
Class clz = point.getClass();
//得到point的字节码中的x变量的字段(所有权限)
Field x = clz.getDeclaredField("x");
//设置x变量的权限为可访问
x.setAccessible(true);
//给ReflectionPoint的对象point中的x设值
x.setInt(point, 4);
//看看是否有对x设值
System.out.println(point.getX());
//得到point的字节码中的y变量字段(公有权限)
Field y = clz.getField("y");
//给ReflectionPoint的对象point中的y成员设值
y.setInt(point, 5);
//打印y
System.out.println(point.getY());
作者:
杨增坤
时间:
2013-8-23 19:02
首先你要把你的
ReflectionPoint的构造方法设置能公有的
,
然后按照这样就可以给字段赋值
public static void main(String[] s) throws Exception {
/*
* 获取公有的成员字段,并获取指定对象该字段的值
*/
Class ClassPoint=ReflectionPoint.class ;
ReflectionPoint rp= (ReflectionPoint)ClassPoint.getConstructor(int.class,int.class).newInstance(1,2);
Field fy=ClassPoint.getField("y");//获取公有的字段(属性)
fy.set(rp, 10);//为指定对象的字段设置值
System.out.println(fy.get(rp));//通过获得的字段,来获得已有对象中该字段的值
/*
* 获得私有成员字段,并获取指定对象该字段的值
*/
Field fx=ClassPoint.getDeclaredField("x");//可以获得私有的字段
fx.setAccessible(true);//设置可操作
fx.set(rp, 20);//为指定对象的字段设置值
System.out.println(fx.get(rp));
}
结果是:
10
20
如果你在你的
ReflectionPoint类有空参数的
构造方法:那么就可以直接用:
Class ClassPoint=ReflectionPoint.class ;
ReflectionPoint rp= (ReflectionPoint)ClassPointnewInstance();
下面的求字段和赋值,就和上面的一样了
如果你
不更更改构造方法为公有的话,那么你就利用单例模式,
设置一个方法,返回一个构造函数的对象,然后我们利用方法的反射,来获取实例对象,然后操作就和上面的一样了。
希望对你有帮助!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2