阅读背景:

反射的方式破解单例模式

来源:互联网 

上篇文章中前两种单例实现方法可以通过反射来进行破解

package com.zkn.newlearn.test.gof;

import static org.junit.Assert.*;

import java.lang.reflect.Constructor;

import org.junit.Test;

import com.zkn.newlearn.gof.singleton.SingletonTest01;
import com.zkn.newlearn.gof.singleton.SingletonTest02;
import com.zkn.newlearn.gof.singleton.SingletonTest05;

public class TestSingleton01 {	
	/**
	 * 破解单例
	 * @throws ClassNotFoundException 
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 */
	@Test
	public void testTest2() throws Exception {
		
		Class clazz = Class.forName("com.zkn.newlearn.gof.singleton.SingletonTest02"); 
		Constructor con = clazz.getDeclaredConstructor(null); //无参结构函数
		con.setAccessible(true);// 设置private权限润饰符为可见
		SingletonTest02 sin1 = (SingletonTest02) con.newInstance();
		SingletonTest02 sin2 = (SingletonTest02) con.newInstance();
		System.out.println(sin1 = sin2); //false
		System.out.println(sin1);
		System.out.println(sin2);
	}
	
}
package com.zkn.newlear




你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: