首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

用反照访问私有成员变量

2012-12-20 
用反射访问私有成员变量用JAVA反射机制访问私有成员变量1. PrivateTester.javapackage com.testpublic cl

用反射访问私有成员变量
用JAVA反射机制访问私有成员变量
1. PrivateTester.java

package com.test;public class PrivateTester {private String name="hello world";public String getName(){return this.name;}}


2. ReflectionTest.java
package com.test;import java.lang.reflect.Field;public class ReflectionTest {/** * @param args * @throws Exception  * @throws   */public static void main(String[] args) throws Exception {PrivateTester pt=new PrivateTester();Class<?> classType=PrivateTester.class;Field field=classType.getDeclaredField("name");field.setAccessible(true);  //压制JAVA访问控制检查String str=(String)field.get(pt);System.out.println(str);field.set(pt, "world");System.out.println(field.get(pt));}}

热点排行