Home » Java programming language

Java Class class getConstructors() method with example

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

Class class getConstructors() method

  • getConstructors() method is available in java.lang package.
  • getConstructors() method is used to return an array of Constructor objects that reflects all the public constructor of the class denoted by this Class object.
  • getConstructors() 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.
  • getConstructors() method may throw a SecurityException at the time of returning an array of Constructor objects.
    SecurityException: In this exception, it may raise when the security manager exists.

Syntax:

    public Constructor[] getConstructors ();

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 the public constructor of this Class.

Note:

  • When the class does not contain public constructor, 0 is returned.
  • When the class is an array class, 0 is returned.
  • When the class reflects primitive or void type, 0 is returned.

Example:

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

import java.lang.reflect.*;

public class GetConstructorsOfClass {
    public static void main(String[] args) throws Exception {
        // It returns the Class object with the given class name
        Class cl = Class.forName("java.lang.StringBuilder");

        // It returns an array of Constructor object
        // that denotes the public constructors of
        // the class StringBuilder
        Constructor con[] = cl.getConstructors();

        // Traversing StringBuilder class
        for (int i = 1; i < con.length; ++i) {
            System.out.print("StringBuilder Class Public Constructors");
            System.out.println(con[i]);
        }
    }
}

Output

StringBuilder Class Public Constructorspublic java.lang.StringBuilder(java.lang.String)
StringBuilder Class Public Constructorspublic java.lang.StringBuilder(int)
StringBuilder Class Public Constructorspublic java.lang.StringBuilder()



Comments and Discussions!

Load comments ↻






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