Wednesday, 14 October 2015

How to use private constructors in Java?

Access private constructors and create object in Java

1. Get constructor list using getDeclaredConstructor() method.

2. Set Constructor list accessible true for the list using setAccessible() method.

3. Obtain object by calling newInstance() method constructor.newInstance().


package core.reflection;
import java.lang.reflect.Constructor;
class PrivateConstructor {
      private PrivateConstructor() {
            System.out.println("private constructor !!");
      }

      @Override
      public String toString() {
            return "I'm private and I'm alright!";
      }
}

public class TestPrivateContructor {
      public static void main(final String[] args) throws Exception {

            /** SecurityException, NoSuchMethodException */
            Constructor<PrivateConstructor> constructor =
                        PrivateConstructor.class.getDeclaredConstructor(new Class[0]);
            // PrivateConstructor.class.getDeclaredConstructor(new Class[0]);

            constructor.setAccessible(true);

            /**
             * IllegalArgumentException, InstantiationException,
             * IllegalAccessException, InvocationTargetException.
             * */
            PrivateConstructor object = constructor.newInstance(new Object[0]);
            // constructor.newInstance();
            System.out.println(object);
      }
}
Output:
      private constructor !!
      I'm private and I'm alright!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...