首先要上被破坏的单例类
package com.mywenwen;
public class Simpleton {
private String username;
private static Simpleton simple;
private Simpleton(){
}
public static Simpleton getSimpleton(){
return simple;
}
static{
simple = new Simpleton();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String toString(){
return this.getClass().getName() + username + " , " + this.hashCode();
}
}
这是一个正常的单例类 私有的构造方法和静态 的返回方法 , 还有一个JavaBean的对象username和自动生成的get/Set方法
然后就是测试段
package com.mywenwen;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class SimpleTest {
public static void main(String[] args) throws Exception{
/*
* 调用 私有方法 强制实例化单例模式
*
*/
Class<?> classSimple = Simpleton.class;
Constructor<?> constructor = classSimple.getDeclaredConstructor();
constructor.setAccessible(true);//取消Java语言访问检查
Object obj = constructor.newInstance();//调用无参构造方法(Private)
Field[] fields = classSimple.getDeclaredFields();//获取字段 , 包括private
for(Field fiel : fields){
//开始执行遍历字段 并且生成设置方法(set + 首字母大写 + 其他字母 )
String s = "set" + fiel.getName().substring(0,1).toUpperCase() + fiel.getName().substring(1);
System.out.println("Execute Method is " + s) ;
if(!isUpdate(fiel))
//判断值是否为 String , int , float 不是就下一个
continue;
Method method = classSimple.getDeclaredMethod(s , String.class);
//执行生成的方法
method.invoke(obj, "wenwen");
}
//输出修改的结果
System.out.println(obj.toString());
}
public static boolean isUpdate(Field field){
Class<?> c = field.getType();
if(c == String.class)
return true;
if(c == Integer.TYPE)
return true;
if(c == float.class)
return true;
return false;
}
}
然后要上运行结果