Constructor getDeclaringClass() method in Java with Examples
Last Updated :
29 Oct, 2019
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:
import java.lang.reflect.Constructor;
public class Main {
public static void main(String[] args)
{
Constructor[] cons
= String. class .getConstructors();
Constructor constructor = cons[ 0 ];
Class classObj
= constructor.getDeclaringClass();
System.out.println( "Source class name : "
+ classObj.getName());
}
}
|
Output:
Source class name : java.lang.String
Program 2:
import java.lang.reflect.Constructor;
import java.util.ArrayList;
public class Main {
public static void main(String[] args)
{
Constructor constructor
= ArrayList. class .getConstructors()[ 0 ];
Class classObj
= constructor.getDeclaringClass();
System.out.println(
"Class Name : "
+ classObj.getName());
}
}
|
Output:
Class Name : java.util.ArrayList
References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#getDeclaringClass(java.lang.Object)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...