简体   繁体   中英

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?

I was trying to create object of Void class

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?

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..."

If you need to run untrusted code then you can use the SecurityManager mechanism to forbid this kind of "rule-breaking".

Because Java has no way of knowing that you intended the class to be used as a singleton. If you want such a class, use an enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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