Home » Java programming language

Java Class class getConstructor() method with example

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

Class class getConstructor() method

  • getConstructor() method is available in java.lang package.
  • getConstructor() method is used to return a Constructor object that reflects the given public constructor of the class denoted by this Class object.
  • getConstructor() 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.
  • getConstructor() 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 getConstructor (Class ...paramType);

Parameter(s):

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

Return value:

The return type of this method is Constructor, it returns Constructor object of the public constructor that meets the given parameter types.

Example:

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

import java.lang.reflect.*;

public class GetConstructorOfClass {
    public static void main(String[] args) throws Exception {
        // Creating an array of Class type
        Class[] cl = new Class[] {
            String.class
        };

        // It return the Constructor object that denotes
        // the public Constructor of the class denoted by
        // the Class object
        Constructor con = String.class.getConstructor(cl);

        // Display public Constructor of String Class
        System.out.println("Constructor of the Class: " + con);
    }
}

Output

Constructor of the Class: public java.lang.String(java.lang.String)



Comments and Discussions!

Load comments ↻






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