Home » Java programming language

Java Class class getDeclaredConstructor() method with example

Class class getDeclaredConstructor() method: Here, we are going to learn about the getDeclaredConstructor() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 11, 2019

Class class getDeclaredConstructor() method

  • getDeclaredConstructor() method is available in java.lang package.
  • getDeclaredConstructor() method is used to return a Constructor object that indicates the given constructor of the class denoted by this Class object.
  • getDeclaredConstructor() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • getDeclaredConstructor() method may throw an exception at the time of returning a Constructor object.
    • NoSuchMethodException: In this exception when a specifying method does not exist.
    • SecurityException: In this exception, it may raise when the security manager exists.

Syntax:

    public Constructor getDeclaredConstructor (Class ...paramType);

Parameter(s):

  • Class ...paramType – represents the parameter array.

Return value:

The return type of this method is Constructor, it returns Constructor object for the constructor with the given set of paramType.

Example:

// Java program to demonstrate the example 
// of Constructor getDeclaredConstructor (Class ...paramType) method of Class 

import java.lang.reflect.*;

public class GetDeclaredConstructorOfClass {
    public static void main(String[] args) throws Exception {
        GetDeclaredConstructorOfClass dc = new GetDeclaredConstructorOfClass();

        Class cl = dc.getClass();

        Class[] cons_argument = new Class[3];
        cons_argument[0] = Integer.class;
        cons_argument[1] = Short.class;
        cons_argument[2] = Long.class;

        Constructor cons = cl.getDeclaredConstructor(cons_argument);
        System.out.println("Declared Constructor:" + cons.toString());

    }
    protected GetDeclaredConstructorOfClass(Integer i, Short s, Long l) {
        this.i = i;
        this.s = s;
        this.l = l;
    }

    public GetDeclaredConstructorOfClass() {
        System.out.println("We are in public Constructor");
    }

    short sh = 10;
    Integer i = new Integer(100);
    Short s = new Short(sh);
    Long l = new Long(30l);
}

Output

We are in public Constructor
Declared Constructor:protected GetDeclaredConstructorOfClass(java.lang.Integer,java.lang.Short,java.lang.Long)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.