I am trying to get the parent class name using
public class ClassA extends Draw{
public ClassA(){
super();
}
.....
}
public class ClassC {
public getParent(Object a_class)
{
String superClass= a_class.getClass().getSuperclass().toString();
}
}
I have got the following error
Exception in thread "main" java.lang.StackOverflowError
at Draw.<init>(Draw.java:2)
at ClassA.<init>(ClassA.java:2)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
at ClassA.<init>(ClassA.java:5)
How to get the parent class Name I need a parent Class name How to get
Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
The Class object has a getName() method that returns the name of the class. So your displayClass() method can call getClass(), and then getName() on the Class object, to get the name of the class of the object it finds itself in.
Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object. Copied!
Use Class.getName()
:
String superClass = a_class.getClass().getSuperclass().getName();
To get just the name and not the package name, use Class.getSimpleName()
:
String superClass = a_class.getClass().getSuperclass().getSimpleName();
However, a_class
is already a Class
instance so you might want to use a_class.getSuperclass()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With