public class Student{
private int id=0;
public int getId(){
return id;
}
}
问题:能否将ReadOnlyClass 类的一个对象,把它的name属性的值由hello改为world?如果能,请写出实现代码。如果不能请说明理由。
答案:可以。利用java的反射
分析:任何一个类,我们可以得到它运行时的Class实例,对于Student类,我们可以通过Student.class得到它运行时的Class实例,接着我们可以通过该类的Class实例去获得这个id属性所对应的Field对象,我们知道对应一个类的属性都一个和它相关的Field对象存在,对于构造方法来说有一个Constructor对象存在,对于一个方法来说有一个对应的Method对象存在。通过这些我们可以利用反射来给这些属性动态的赋值。
首先我们看看JDK API中Class类的两个方法的描述:
public Field getField(String name)throws NoSuchFieldException,SecurityException
Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired field.The field to be reflected is determined by the algorithm that follows. Let C be the class represented by this object:If C declares a public field with the name specified, that is the field to be reflected.If no field was found in step 1 above, this algorithm is applied recursively to each direct superinterface of C. The direct superinterfaces are searched in the order they were declared.If no field was found in steps 1 and 2 above, and C has a superclass S, then this algorithm is invoked recursively upon S. If C has no superclass, then a NoSuchFieldException is thrown.(翻译:返回一个Field对象,它返回此Class对象所表示的类或接口的指定public属性字段,id参数是一个int,用于指定所需字段的简称。要反映的字段由下面的算法确定。设C为次对象所表示的类:如果C声明一个带有指定名的公共字段,则它就是要反映的字段。如果在第1步中没有找到任何字段,则该算法被递归的应用与C的每一个直接超接口。直接超接口按其声明的顺序进行搜索,如果在第1,2两步没有找到任何字段,且C有一个超类S,则在S上递归调用该算法,如果C没有超类则抛出NoSuchFieldException.)
public Field getDeclaredField(String name) throws NoSuchFieldException,SecurityException
Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field. Note that this method will not reflect the length field of an array class.(翻译:返回一个Field对象,该对象反映次Class对象所表示的类或接口的指定以声明字段,id参数是一个int,它指定所需字段的简称,次方法不反映数组类的length字段。)
从上面的JDK API我们知道,要得到id属性对应的Filed对象,我们只能调用class的getDeclaredField方法,因为getField方法只能得到一个类的public的属性对应的Field对象,而这里的name属性是private的,我们通过Class的getDeclaredField方法得到id属性对应的Field对象后,我们就可以调用Filed对象的set方法给id赋值。由于id是私有属性,我们要想知道我们到底改变了id的值没有,我们可以通过Filed类的父类的setAccessible(boolean flag)方法类限制java语言 的访问限制。对于setAccessible方法我们看JDK文档:
public void setAccessible(boolean flag)throws SecurityException
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission. A SecurityException is raised if flag is true but accessibility of this object may not be changed (for example, if this element object is a Constructor object for the class Class). (翻译:将此对象的 accessible标志设置为指示的布尔值,值为true则指示反射的对象在使用时应该取消java语言访问检查,值为False则指示反射的对象应该事实java语言访问检查。
首先,如果存在安全管理器,则在ReflectPermission("suppressAccessChecks"))权限下调用checkPermission方法。如果falg为true,并且不能更改次对象的可访问性(例如,如果次元素对象是Class类的Constructor对象),。则会引发SecurityException。如果次对象是java.lang.Class类的Constructor对象,并且flag为true,则会引发SecurityException
所以:
public class StudentRef{
public static void main(String[] args){
Student stu=new Student();
Class<?> cla=Student.class ;
Field filed = cla.getDeclaredField("id");
field.setAccessible(true);
field.set(stu,2);
System.out.println(stu.getId());
}
}
总结:对于一个类,它只有唯一个Class对象,它来标识这个对象,这个Class对象就能够获得这个类的结构上的特征。那那么通过Class对象就可以来获得这个类相应的构造方法,属性等。
获得某一个类它的Class对应有4种方法:
* 使用类的.class语法
* 使用类的对象的getClass()方法,getClass()方法在Object类里定义的
* 通过Class对象的forName()方法
* 对于包装类,可以通过.TYPE方法
通过类的反射机制,我们可以改变只读的私有(private)属性值