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

java.lang.SecurityException: Can not make a java.lang.Class constructor accessible
    at java.lang.reflect.AccessibleObject.setAccessible0(AccessibleObject.java:118)
    at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:108)

 

because of following snippets from AccessibleObject.java

private static void setAccessible0(AccessibleObject obj, boolean flag)
    throws SecurityException
{
    if (obj instanceof Constructor && flag == true) {
        Constructor c = (Constructor)obj;
        if (c.getDeclaringClass() == Class.class) {
        throw new SecurityException("Can not make a java.lang.Class" +
                        " constructor accessible");
        }
    }
    obj.override = flag;
}

 

The complete code

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class InstantiatePrivateConstructor {
    public static void main(String[] args) {
        String systemClassName = "java.lang.System";
        String runtimeClassName = "java.lang.Runtime";
        String classClassName = "java.lang.Class";
        try {
            Class system = Class.forName(systemClassName);
            Constructor sysConstructor = system.getDeclaredConstructor();
            sysConstructor.setAccessible(true);
            System sysObject = (System) sysConstructor.newInstance();
            Field[] systemFields = sysObject.getClass().getFields();
            System.out.println("Class Name: " + systemClassName);
            System.out
                    .println("-------------------------------------------------");
            System.out.println("sysObject: " + sysObject);
            System.out.println("systemFields length: " + systemFields.length);
            for (int i = 0; i < systemFields.length; i++) {
                System.out.println("Field Name: " + systemFields[i].getName());
                System.out.println("Field Type: " + systemFields[i].getType());
            }
            System.out
                    .println("===================================================");
            System.out.println();
            Class runtime = Class.forName(runtimeClassName);
            Constructor runConstructor = runtime.getDeclaredConstructor();
            runConstructor.setAccessible(true);
            Runtime runObject = (Runtime) runConstructor.newInstance();
            Field[] runFields = runObject.getClass().getFields();
            System.out.println("Class Name: " + runtimeClassName);
            System.out
                    .println("-------------------------------------------------");
            System.out.println("runObject: " + runObject);
            System.out.println("runFields length: " + runFields.length);
            for (int i = 0; i < runFields.length; i++) {
                System.out.println("Field Name: " + runFields[i].getName());
                System.out.println("Field Type: " + runFields[i].getType());
            }
            System.out
                    .println("===================================================");
            System.out.println();
            Class clss = Class.forName(classClassName);
            Constructor classConstructor = clss.getDeclaredConstructor();
            System.out.println("Class Name: " + classClassName);
            System.out
                    .println("-------------------------------------------------");
            System.out.println("Now you will get Exception for below line");
            System.out.println();
            Class classObject = (Class) classConstructor.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 

Output

Class Name: java.lang.System
-------------------------------------------------
sysObject: java.lang.System@9304b1
systemFields length: 3
Field Name: in
Field Type: class java.io.InputStream
Field Name: out
Field Type: class java.io.PrintStream
Field Name: err
Field Type: class java.io.PrintStream
===================================================
Class Name: java.lang.Runtime
-------------------------------------------------
runObject: java.lang.Runtime@a90653
runFields length: 0
===================================================
Class Name: java.lang.Class
-------------------------------------------------
Now you will get Exception for below line
java.lang.IllegalAccessException: Class in.sblog.java.reflection.InstantiatePrivateConstructor can not access a member of class java.lang.Class with modifiers "private"
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:505)
    at in.sblog.java.reflection.InstantiatePrivateConstructor.main(InstantiatePrivateConstructor.java:59)

 

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

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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