码迷,mamicode.com
首页 > 其他好文 > 详细

反射单例

时间:2014-10-08 01:17:34      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   java   for   sp   

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

反射单例

标签:style   blog   color   io   os   ar   java   for   sp   

原文地址:http://www.cnblogs.com/awq-nice/p/4009991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!