您的位置:首页 > 编程语言 > Java开发

暴力反射创建多个单例模式的实例对象

2014-05-12 16:41 411 查看
既然暴力反射可以得到被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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息