Singleton模式指出,一个类可以有一个实例,并且不允许创建多个实例。为此,我们将类的构造函数设为私有,并通过静态方法返回实例。但是使用反射,我们仍然可以通过修改构造函数作用域来创建一个类的多个实例。请参阅下面的示例-
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Tester {
public static void main(String[] args) throws
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
A a = A.getInstance();
A b = null;
Constructor<?>[] constructors = A.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
//将私有构造函数设为公共
constructor.setAccessible(true);
b = (A) constructor.newInstance();
break;
}
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
class A implements Serializable {
private static A a;
private A(){}
public static A getInstance(){
if(a == null){
a = new A();
}
return a;
}
}输出结果
705927765 366712642
在这里您可以看到,我们已经创建了Singleton类的另一个对象。让我们看看如何防止这种情况-
使用枚举而不是类创建A。
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
public class Tester {
public static void main(String[] args) throws
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
A a = A.INSTANCE;
A b = A.INSTANCE;
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
enum A implements Serializable {
INSTANCE;
}输出结果
705927765 705927765