Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent class name using getClass().getSuperclass()? [closed]

Tags:

java

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

like image 689
Sivakumar M Avatar asked Dec 24 '13 09:12

Sivakumar M


People also ask

What is getClass () getName () in Java?

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.

How do you reference a parent class in Java?

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.

How do you find the class name for a subclass?

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.

How do I find the class name of an object?

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!


1 Answers

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.

like image 147
Tobias Avatar answered Nov 12 '22 14:11

Tobias