Getting the name of the child class in the constructor of the base class

Suppose I have an abstract class

public abstract class Foo

and one constructor

public Foo()
{
}

      

Given that this constructor had to be called from the construct of the child class, is there a way to restore the name of this child class in the constructor Foo

?

I would rather not do something nasty with the stack trace.

+3


source to share


6 answers


If you want a class name like this getClass().getSimpleName()

, just use

public Foo() {
  declaredClassname = this.getClass().getSimpleName();
}

      



due to polymorphism, it will always call getClass () from the child class.

+3


source


You can use the following:



public Foo()
{
    System.out.println(this.getClass().getSimpleName())
}

      

+1


source


Sure:

getClass()

      

But note that the child class instance (i.e. its fields) is still not initialized and will be executed after the base class constructor. Also, don't call overridden methods for the same reason.

Executing the constructor of the child class:

  • super () or super (...) constructor
  • which are initialized Xxx xxx = ...;

  • the rest of the constructor code
+1


source


You can get it in the constructor of the subclass and pass it as a String to the constructor of the superclass:

public foo(String className)
{
}

//subclass constructor
public subclass()
{
     super("subclass");
}

      

Or you could do:

public foo(String className)
{
}

//subclass constructor
public subclass()
{
     super(this.getClass().getSimpleName());
}

      

0


source


If you are in a class hierarchy and want to know which class is actually created, you can use getClass (). If you want to know the "top-most" class instead of the "bottom-most" class, iterate over the superclasses until you find your own class.

import static java.lang.System.err;
abstract class A {
    protected A() {
        err.format("%s %s%n", getClass().getName(), getTopMostSubclass().getName());
    }
    Class<? extends A> getTopMostSubclass() {
        Class<?> previousClass = getClass(), currentClass;
        while (!A.class.equals(currentClass = previousClass.getSuperclass()))
            previousClass = currentClass;
        return (Class<? extends A>) previousClass;
    }
}
class B extends A {}
class C extends B {}
public class Main {
    public static void main(final String... args) {
        new B(); // prints B B
        new C(); // prints C B
    }
}

      

0


source


You can simply call the getClass () function on the object you want to know the class for. So in your case, you would do something like this:

abstract class ParentClass {
    public ParentClass() {
        System.out.println(this.getClass().getName());
    }
    public String doSomething() {
        return "Hello";
    }
}

class ChildClass extends ParentClass {
}

...
...

ChildClass obj = new ChildClass();// will output  ChildClass

      

0


source







All Articles