首页 > 代码库 > 反射单例
反射单例
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
反射单例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。