首页 > 代码库 > 反射单例

反射单例

package com.mycon.app;import java.lang.reflect.Constructor;import java.util.Arrays;public class SingletonTest {        @SuppressWarnings("rawtypes")    public static void main(String[] args) {        Singleton singleton = Singleton.getInstance();        System.out.println(singleton.getName());        Singleton s2 = null;        try {            Constructor[] constructors = Singleton.class.getDeclaredConstructors();            System.out.println(constructors.length);            for (Constructor c : constructors) {                System.out.println(c.getName());                Class[] params = c.getParameterTypes();                System.out.println("Class params:" + Arrays.toString(params));                if (params.length == 1) {
            // 取消语法检查 c.setAccessible(Boolean.TRUE); s2
= (Singleton)c.newInstance(new Object[]{"Swift"}); break; } } } catch (Exception e) { e.printStackTrace(); } System.out.println("s2:" + s2); System.out.println("s2-name:" + s2.getName()); System.out.println("s1-name:" + singleton.getName()); }}    

package com.mycon.app;public class Singleton {        private String name;    private Singleton(String name) {        this.name = name;    }        public static Singleton getInstance() {        return SingletonHolder.SINGLETON_HOLDER;    }    private static class SingletonHolder {        public static final Singleton SINGLETON_HOLDER = new Singleton("Jack");    }        public String getName() {        return name;    }}

ouput:

Jack
2
com.mycon.app.Singleton
Class params:[class java.lang.String, class com.mycon.app.Singleton]
com.mycon.app.Singleton
Class params:[class java.lang.String]
s2:com.mycon.app.Singleton@4b8efa2f
s2-name:Swift
s1-name:Jack

反射单例