Reputation: 5922
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?
Upvotes: 1
Views: 415
Reputation: 310926
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.
Upvotes: 2
Reputation: 122364
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".
Upvotes: 5