您的位置:首页 > 其它

创建一个类的实例,修改类中定义为private的变量的值

2015-12-26 01:27 381 查看
import java.lang.reflect.*;

/**
*   public class ReadOnlyClass{
*       private String name = "hello";
*       public String getName(){
*           return name;
*   }
*创建ReadOnly的实例,能否将name的值改为world
*可以实现 通过反射
**/
class ReadOnlyClass
{

public static void main(String[] args)
{
ReadOnly roc = null;
try
{
//通过Class类中静态方法forName获得ReadOnly的字节码文件
Class c  = Class.forName("ReadOnly");
//获的ReadOnly类的无参构造方法
Constructor cons = c.getDeclaredConstructor();
if(!cons.isAccessible()){
cons.setAccessible(true);
}
//通过无参构造方法创建实例
roc = (ReadOnly)cons.newInstance();

//roc = (ReadOnly)c.newInstance();//如果构造函数私有化,则该方法抛出IllegalAccessException
//获得类中name成员变量
Field f = c.getDeclaredField("name");
if(!f.isAccessible())
f.setAccessible(true);
f.set(roc,"world");
System.out.println(f.get(roc));
//获得类中show方法
Method m = c.getDeclaredMethod("show");
if(!m.isAccessible())
m.setAccessible(true);
m.invoke(roc);
//获取全部成员变量
Field[] fields = c.getDeclaredFields();
System.out.println(c.getName()+"中存在的成员变量有"+fields.length+"个,具体情况如下:");
for(int i = 0; i< fields.length; i++){
System.out.println(fields[i]);
}
//获取全部方法
Method[] methods = c.getDeclaredMethods();
System.out.println(c.getName()+"中存在的方法有"+methods.length+"个,具体情况如下:");
for(Method method : methods){
StringBuffer sb = new StringBuffer();
Type[] types = method.getGenericParameterTypes();
for(int i =0; types.length > 0 && i < types.length;i++){
if(i < types.length-1 ){
sb.append(types[i]+",");
}else{
sb.append(types[i]);
}

}
System.out.println("方法声明:"+Modifier.toString(method.getModifiers())+" "+method.getReturnType()+" "
+method.getName()+"("+sb.toString()+")");
}

}
catch (Exception e)
{
e.printStackTrace();
}

}

}

class ReadOnly
{
//私有化了构造函数
private ReadOnly(){}
//私有化成员变量
private String name = "hello";
//私有化的静态成员变量
private static final String TAG = "这是我的标签";

//公开的访问变量的方法
public String getName(){

return name;
}

//私有的成员方法
private void show(){
System.out.println("private method show------");
}

//私有化的静态方法
private static void main(String str,int i,Class clazz){
System.out.println("private static method main"+str);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射 Method Field Modifier