推荐:Java设计模式汇总
反射破坏单例模式以及如何防御
需要了解实现单例模式的各种方法,可以参考下方这篇博客。
设计模式-单例模式(Singleton Pattern)
单例模式类Singleton,是使用静态内部类实现的单例模式。
package com.kaven.design.pattern.creational.singleton;
public class Singleton{
private Singleton(){}
public static Singleton getInstance(){
return Inner.instance;
}
private static class Inner{
private static final Singleton instance = new Singleton();
}
}
接下来,使用反射来破坏单例模式。
package com.kaven.design.pattern.creational.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectionDestroyTest {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class objectClass = Singleton.class;
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
Singleton instance = Singleton.getInstance();
Singleton newInstance = (Singleton) constructor.newInstance();
System.out.println(instance);
System.out.println(newInstance);
System.out.println(instance == newInstance);
}
}
因为在单例模式中的构造器是私有的,在Singleton类外部是不能随便调用的,但是通过反射就不一定了,通过这段代码constructor.setAccessible(true)
便可以得到构造器的访问权。
结果:
com.kaven.design.pattern.creational.singleton.Singleton@4554617c
com.kaven.design.pattern.creational.singleton.Singleton@74a14482
false
很明显,反射确实破坏了单例模式。
我们如何应对呢?
即便是通过反射来创建实例,也是调用类中的构造器来实现的,所以我们可以在构造器中做文章。
改造Singleton类
中的私有构造器如下:
package com.kaven.design.pattern.creational.singleton;
public class Singleton{
private Singleton(){
if(Inner.instance != null){
throw new RuntimeException("单例模式禁止反射创建实例!");
}
}
public static Singleton getInstance(){
return Inner.instance;
}
private static class Inner{
private static final Singleton instance = new Singleton();
}
}
结果:
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.kaven.design.pattern.creational.singleton.ReflectionDestroyTest.main(ReflectionDestroyTest.java:12)
Caused by: java.lang.RuntimeException: 单例模式禁止反射创建实例!
at com.kaven.design.pattern.creational.singleton.Singleton.<init>(Singleton.java:6)
... 5 more
很显然报异常了,这样便防止了这种方法实现的单例模式被反射破坏。
饿汉式
实现的单例模式都可以这样来防止单例模式被反射破坏。
懒汉式实现的单例模式是不可以防止被反射破坏的。
用双重检查锁式
实现的单例模式来进行测试,其他的懒汉式
实现的单例模式同理。
package com.kaven.design.pattern.creational.singleton;
public class Singleton {
private static volatile Singleton instance ;
private Singleton(){
if(instance != null){
throw new RuntimeException("单例模式禁止反射创建实例!");
}
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
上面的测试方法是没有问题的。
我们改一改测试方法:
package com.kaven.design.pattern.creational.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectionDestroyTest {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class objectClass = Singleton.class;
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
Singleton newInstance = (Singleton) constructor.newInstance();
Singleton instance = Singleton.getInstance();
System.out.println(instance);
System.out.println(newInstance);
System.out.println(instance == newInstance);
}
}
很明显,我们把通过反射创建实例
和调用静态方法getInstance()
获得实例的位置互换了,所以一开始通过反射创建实例
调用构造器,此时构造器中的判断instance != null
是无用的,所以这种方法是不适用懒汉式
实现的单例模式来防止被反射破坏的。
结果也很明显:
com.kaven.design.pattern.creational.singleton.Singleton@4554617c
com.kaven.design.pattern.creational.singleton.Singleton@74a14482
false
我们可以使用信号量吗?
代码如下:
package com.kaven.design.pattern.creational.singleton;
public class Singleton {
private static volatile Singleton instance ;
private static boolean flag = true;
private Singleton(){
if(flag){
flag = false;
}
else{
throw new RuntimeException("单例模式禁止反射创建实例!");
}
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
这样我们是不是只能调用一次构造器了,所以也就可以防止反射了?
反射可以获得私有构造器的访问权,难道就不能获得私有静态变量的访问权吗?
很显然是可以的,所以这种方法也是行不通的。
如果定义信号量为final
呢?就更不行了吧,因为都不能更改。
测试:
package com.kaven.design.pattern.creational.singleton;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectionDestroyTest {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
Class objectClass = Singleton.class;
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
Singleton instance = Singleton.getInstance();
Field flag = objectClass.getDeclaredField("flag");
flag.setAccessible(true);
flag.set(instance , true);
Singleton newInstance = (Singleton) constructor.newInstance();
System.out.println(instance);
System.out.println(newInstance);
System.out.println(instance == newInstance);
}
}
结果:
com.kaven.design.pattern.creational.singleton.Singleton@1540e19d
com.kaven.design.pattern.creational.singleton.Singleton@677327b6
false
很显然出问题了。
所以懒汉式实现的单例模式是不可以防止被反射破坏的。
评论中的例子
例一:
private Singleton() {
// 防止反射对单例的破坏
if(instance!=null){ // 单例已有实例
throw new RuntimeException("禁止使用反射创建单例");
}
instance = this;
}
测试:
package com.kaven.system;
import lombok.SneakyThrows;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Singleton {
private static volatile Singleton instance ;
private Singleton() throws InterruptedException {
// 防止反射对单例的破坏
if(instance!=null){ // 单例已有实例
throw new RuntimeException("禁止使用反射创建单例");
}
// 如果执行到这里,需要等待一段时间才能继续执行,比如时间片用完了
Thread.sleep(100);
instance = this;
System.out.println(this + " " + Thread.currentThread().getName());
}
public static Singleton getInstance() throws InterruptedException {
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException, InterruptedException {
Class objectClass = Singleton.class;
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
Thread thread = new Thread(new Singleton.myRunnable());
thread.setName("kaven");
thread.start();
constructor.newInstance();
}
static class myRunnable implements Runnable{
@SneakyThrows
@Override
public void run() {
Singleton.getInstance();
}
}
}
结果:
还是可以破坏单例模式的,因为我们不知道时间片什么时候用完,或者在执行过程中遇到什么问题。
例二:
private Singleton(){
synchronized (Singleton.class) {
// 防止反射对单例的破坏
if (instance != null) { // 单例已有实例
throw new RuntimeException("禁止使用反射创建单例");
}
instance = this;
}
}
测试:
package com.kaven.system;
import lombok.SneakyThrows;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Singleton {
private static volatile Singleton instance ;
private static boolean throwException = true;
private Singleton(){
synchronized (Singleton.class) {
// 防止反射对单例的破坏
if (instance != null) { // 单例已有实例
throw new RuntimeException("禁止使用反射创建单例");
}
System.out.println(this + " " + Thread.currentThread().getName());
// 如果出现异常,异常结束时会释放掉锁
if(Singleton.throwException) throw new RuntimeException();
instance = this;
}
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Class objectClass = Singleton.class;
Constructor constructor = objectClass.getDeclaredConstructor();
constructor.setAccessible(true);
Thread thread = new Thread(new Singleton.myRunnable());
thread.setName("kaven");
thread.start();
Singleton singleton = null;
try {
singleton = (Singleton) constructor.newInstance();
} catch (Exception e){
e.printStackTrace();
} finally {
// 虽然还是null
System.out.println(singleton);
}
}
static class myRunnable implements Runnable{
@SneakyThrows
@Override
public void run() {
Thread.sleep(50);
Singleton.throwException = false;
Singleton singleton = Singleton.getInstance();
System.out.println(singleton);
}
}
}
结果:
虽然打印出来了两个实例,但只有一个实例可用,这种情况是否符合单例模式呢?大家可以相互讨论一下。
如果有说错的地方,请大家不吝赐教(记得留言哦~~~~)。