Java: can a parent class statically retrieve the class name of a child class?

Referring to Java, I want to know the class name of the current class statically A is the parent of B I think there is a static string containing the class name of the current class in a (parent class), but when this static string is referenced in B (subclass), it should contain the name of class B. is it possible?

Example:

public class Parent {

protected static String MY_CLASS_NAME = ???
.
.
.
}

public class Child extends Parent {

public void testMethod() {
     if (MY_CLASS_NAME.equals(getClass().getName())) {
        System.out.println("We're equal!");
     }
}

}

Solution

The only way I know is as follows:

class Parent {
    private final String className;
    protected Parent(String className) {
         this.className = className;
    }
}

public class Child extends Parent {
    public Child() {
        super("Child");
    }
}

BTW you can even use the new throwable () Get getstacktrace () in the constructor of parentheses In this case, you don't even have to force all children to pass their names on to their parents

class Parent {
    private final String className;
    protected Parent() {
         StackTraceElement[] trace = new Throwable().getStackTrace();
         this.className = trace[1].getClassName();
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
***
下一篇>>