Home » Java programming language

Java Class class getDeclaredConstructors() method with example

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

Class class getDeclaredConstructors() method

  • getDeclaredConstructors() method is available in java.lang package.
  • getDeclaredConstructors() method is used to return an array of Constructor object that indicates the types of constructor defined by the class denoted by this Class object (Constructor may be public, private, protected or default).
  • getDeclaredConstructors() 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.
  • getDeclaredConstructors() method may throw an exception at the time of returning a Constructor[].
    SecurityException: In this exception, it may raise when the security manager exists.

Syntax:

    public Constructor[] getDeclaredConstructors ();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Constructor[], it returns an array of Constructor object denoting all declared constructor (private, public, protected, default) of this Class.

Example:

// Java program to demonstrate the example 
// of Constructor [] getDeclaredConstructors() method of Class

import java.lang.reflect.*;

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

        Class cl = dc.getClass();

        Constructor[] cons = cl.getDeclaredConstructors();

        for (int i = 0; i < cons.length; ++i)
            System.out.println("Declared Constructors :" + cons[i].toString());

    }
    private GetDeclaredConstructorsOfClass(Integer i, Short s, Long l) {
        this.i = i;
        this.s = s;
        this.l = l;
    }

    public GetDeclaredConstructorsOfClass() {

        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 Constructors :private GetDeclaredConstructorsOfClass(java.lang.Integer,java.lang.Short,java.lang.Long)
Declared Constructors :public GetDeclaredConstructorsOfClass()


Comments and Discussions!

Load comments ↻





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