首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Runtime各异定非是单例的

2013-11-13 
Runtime不一定非是单例的。package org.tsw.reflectimport java.lang.reflect.Constructorpublic class M

Runtime不一定非是单例的。
package org.tsw.reflect;import java.lang.reflect.Constructor;public class Mainer {public static void main(String[] args) throws Exception {// Runtime是单例模式中最经典的一个例子。// 通常我们是通过静态方法获取到一个实例的。Runtime rt1 = Runtime.getRuntime();rt1.exec("msconfig");// 打开微软管理器//Runtime rt = new Runtime(); 不能调用私有构造器实例化// 可以通过反射机制获取Runtime的一个实例Constructor<?> constructor = Runtime.class.getDeclaredConstructors()[0];// 通过查看源代码我们知道Runtime只有一个私有构造器constructor.setAccessible(true);// 抑制Java语言访问检查Runtime rt2 = (Runtime) constructor.newInstance();// 实例化一个Runtimert2.exec("calc");// 用一下// 检测一下这两个Runtime实例是否是同一个实例,即验证Runtime是否是单例System.out.println(rt1 == rt2 ? "是单例" : "不是单例");// 打印的是不是单例,即两个不同的实例}}

?

1 楼 cs6641468 2013-10-31   单例能解决的事,没有并发风险,非要声明多个实例,有何意义?

热点排行