
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
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());
- Related Questions & Answers
- How to call one constructor from another in Java?
- How to call the constructor of a superclass from a constructor in java?
- Can we have a constructor private in java?
- Java Program to Call One Constructor from another
- What is the purpose of private constructor in Java?
- Can we declare a constructor as private in Java?
- Where and how can I create a private constructor in Java?
- How to call a static constructor or when static constructor is called in C#?
- How to call parent constructor in child class in PHP?
- How to call another enum value in an enum's constructor using java?
- Order of Constructor/ Destructor Call in C++
- How to call the constructor of a parent class in JavaScript?
- Can we call a constructor directly from a method in java?
- How to explicitly call base class constructor from child class in C#?
- Private Keyword in Java
Advertisements