本帖最后由 yanglfree 于 2013-10-25 09:55 编辑
- <P>
- <P>public class ReflectDemo {
- public static void main(String[] args) throws Exception{
- ReflectPoint fp = new ReflectPoint(3, 4);
- Field fieldX = fp.getClass().getDeclaredField("x");
- Field fieldY = fp.getClass().getDeclaredField("y");
- fieldX.setAccessible(true);//暴力反射,可以访问私有的成员变量x
- System.out.println(fieldX.get(fp));
- System.out.println(fieldY.get(fp));
- change(fp);
- System.out.println(fp.toString());
- Method me = fp.getClass().getMethod("toString", String.class);
- }</P>
- <P>
- </P>
- <P> public static void change(Object obj) throws Exception{
- Field [] fields = obj.getClass().getFields();
- for (Field field : fields) {
- if (field.getType() == String.class) {
- String oldStr = (String) field.get(obj);
- String newStr = oldStr.replace('b', 'a');
- field.set(obj, newStr);
- }
- }
- }</P>
- <P>}
- </P>
复制代码 关于暴力反射,fieldX.setAccessible(true);暴力反射除了获取私有成员变量的值外,还有其他作用吗? |