- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- public class Singleton{
- private static Singleton INSTANCE=new Singleton();
- private Singleton()throws RuntimeException{
- if(INSTANCE!=null){
- throw new RuntimeException("已经创建");
- }
- }
- public static Singleton getInstance(){
- return INSTANCE;
- }
- public static void main(String ...strings) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
- {
- Singleton instance=Singleton.getInstance();
- Singleton ins=Singleton.getInstance();
- if(instance==ins)
- {
- System.out.println("==");
- }
- Class c=Class.forName("Singleton");
- Constructor t=c.getDeclaredConstructor();
- t.setAccessible(true);
- Singleton s=(Singleton) t.newInstance();
- if(instance==s)
- {
- System.out.println("==");
- }
- else{
- System.out.println("!=");
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0203201511819.html
来源: http://www.codesnippet.cn/detail/0203201511819.html