既然暴力反射可以得到被private修饰的成分,那么就应该有获得私有构造函数的方法,查看api文档发现确实有getDeclaredConstructor()方法
package day4;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test7 {
/**
* @param args
* 暴力反射获取单例的构造方法创建实力对象
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Single s = Single.getInstance();
Constructor constructor = s.getClass().getDeclaredConstructor();
constructor.setAccessible(true);
Single s2 = (Single)constructor.newInstance();
System.out.println(s2.x);
}
}
class Single{
private Single(){};
public static int x = 4;
private static Single s = new Single();
public static Single getInstance(){
return s;
}
}