Call Private Constructor in Java



The method java.lang.Class.getDeclaredConstructor() can be used to obtain the constructor object for the private constructor of the class. The parameter for this method is a Class object array that contains the formal parameter types of the constructor.

A program that demonstrates this is given as follows −

Example

 Live Demo

package Test;
import java.lang.reflect.*;
public class Demo {
   String str;
   Double d;
   public Demo(String str, Double d) {
      this.str = str;
      this.d = d;
   }
   public static void main(String[] args) {
      try {
         Demo obj = new Demo("Apple", 55.983);
         Class c = obj.getClass();
         Class[] arguments = new Class[2];
         arguments[0] = String.class;
         arguments[1] = Double.class;
         Constructor constructor = c.getDeclaredConstructor(arguments);
         System.out.println("Constructor = " + constructor.toString());
      } catch(NoSuchMethodException e) {
         System.out.println(e.toString());
      } catch(SecurityException e) {
         System.out.println(e.toString());
      }
   }
}

output

Constructor = public Test.Demo(java.lang.String,java.lang.Double)

Now let us understand the above program.

An object of class Demo is created in the main() method. Then the array arguments[] stores the String.Class and Double.Class objects. Finally, the method getDeclaredConstructor() can be used to obtain the constructor object and this is displayed. A code snippet which demonstrates this is as follows −

Demo obj = new Demo("Apple", 55.983);
Class c = obj.getClass();
Class[] arguments = new Class[2];
arguments[0] = String.class;
arguments[1] = Double.class;
Constructor constructor = c.getDeclaredConstructor(arguments);
System.out.println("Constructor = " + constructor.toString());
Updated on: 2020-06-25T12:23:27+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements