Instantiate object from a Class which contains private constructor

We know that we cannot make any object if the Class contains private constructor but this is not true until a special care is not taken to the private constructor. This tutorial shows an example how to create instance using Reflection even if the classes have private constructors. Though if the special care taken to the prvate constructor then you will not be able to create an instance.
The below example creates instances from classes java.lang.System and java.lang.Runtime but you will not be able to create any instance from java.lang.Class because it cheks some security permission hence it will throw Security exception.

While accessing Class’s private constructor it throws following exception

 

because of following snippets from AccessibleObject.java

 

The complete code

 

Output

 

That’s all. Thanks for reading. Please do not forget to leave a comment.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.