简体   繁体   English

为什么我可以创建多个具有反射的单例实例?

[英]Why can I create more than one instance of a singleton with reflection?

Why java doesn't stop you to instantiate any singleton class object? 为什么Java不会阻止您实例化任何单例类对象?

I was trying to create object of Void class 我试图创建Void类的对象

java.lang.Void

I wrote this code to create two instance 我写了这段代码来创建两个实例

try{
    Class clazz = Void.class;
    Constructor cons = clazz.getDeclaredConstructor();
    cons.setAccessible(true);
    Void s2 = (Void) cons.newInstance(); 
    System.out.println(s2);
    Void s3 = (Void) cons.newInstance(); 
    System.out.println(s3);

}catch (Exception e) {
    e.printStackTrace();
} 

Can anybody explain - why this is allowed in java? 谁能解释-为什么在Java中允许这样做?

Using reflection like that allows you to sidestep the normal protection mechanisms and do stuff like call private constructors and methods you wouldn't normally have access to. 使用这样的反射,您可以避开常规的保护机制,并执行通常无法访问的调用私有构造函数和方法之类的操作。 Java doesn't allow you to instantiate a class via a private constructor without the setAccessible call - essentially that means "I know I'm not supposed to do this but..." Java不允许您在没有setAccessible调用的情况下通过私有构造函数实例化一个类-本质上来说,这意味着“我知道我不应该这样做,但是...”

If you need to run untrusted code then you can use the SecurityManager mechanism to forbid this kind of "rule-breaking". 如果您需要运行不受信任的代码,则可以使用SecurityManager机制来禁止这种“破坏规则”。

Because Java has no way of knowing that you intended the class to be used as a singleton. 因为Java无法知道您打算将类用作单例。 If you want such a class, use an enum. 如果要使用此类,请使用枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM