Constructor getDeclaringClass() method in Java with Examples

The constructor class provides information about a single constructor for a class and it also provides access to that constructor.
The getDeclaringClass() method of java.lang.reflect.Constructor is used to return the class object representing the class that declares the constructor represented by this object. This method returns the name of the source class of this constructor.

Syntax:

public Class<T> getDeclaringClass()

Parameters: This method accepts nothing.

Return: This method returns an object representing the declaring class of the underlying member.

Below programs illustrate getDeclaringClass() method:
Program 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate getDeclaringClass() method
  
import java.lang.reflect.Constructor;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // get Constructor object array
        // from  String class object
        Constructor[] cons
            = String.class.getConstructors();
        Constructor constructor = cons[0];
  
        // apply getDeclaringClass method
        Class classObj
            = constructor.getDeclaringClass();
  
        // print result
        System.out.println("Source class name : "
                           + classObj.getName());
    }
}

chevron_right


Output:

Source class name : java.lang.String

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate getDeclaringClass() method
  
import java.lang.reflect.Constructor;
import java.util.ArrayList;
  
public class Main {
  
    public static void main(String[] args)
    {
  
        // get Constructor object for class object
        Constructor constructor
            = ArrayList.class.getConstructors()[0];
  
        // apply getDeclaringClass method
        Class classObj
            = constructor.getDeclaringClass();
  
        // print result
        System.out.println(
            "Class Name : "
            + classObj.getName());
    }
}

chevron_right


Output:

Class Name : java.util.ArrayList

References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getDeclaringClass(java.lang.Object)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.