In reference to Java, I would like to statically know the class name of the current class. A is the parent class of B. I would like to have a static String in A (parent class) which contains the class name of the current class, but when this static String is referenced in B (child class), it should contain the class name of B. Is this 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!");
}
}
}
Parent and Child classes having same data member in Java Java 8 Server Side Programming Programming 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.
If a parent reference variable is holding the reference of the child class and we have the “value” variable in both the parent and child class, it will refer to the parent class “value” variable, whether it is holding child class object reference.
The reference variable of the Parent class is capable to hold its object reference as well as its child object reference. In Java, methods are virtual by default (See this for details).
Retrieving a Class Name in Java 1 Overview. In this tutorial, we'll learn about four ways to retrieve a class's name from methods on the Class API: getSimpleName (), getName (), getTypeName () and getCanonicalName (). 2 Retrieving Simple Name. Let's begin with the getSimpleName () method. ... 3 Retrieving Other Names. ... 4 Conclusion. ...
The only way I know is the following: create protected constructor that accepts String in parent class.
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 improve this using new Throwable().getStackTrace()
in paren's custructor. In this case you even do not have to enforce all children to pass their name to parent.
class Parent {
private final String className;
protected Parent() {
StackTraceElement[] trace = new Throwable().getStackTrace();
this.className = trace[1].getClassName();
}
}
No, that's not possible. There's only one copy of the static String (per ClassLoader), but you can have multiple subclasses.
You can however have a static field per (sub-)class, and then use a method
public class Child extends Parent {
private static final String NAME = "some alias";
@Override
public String getName() {
return NAME;
}
}
This is a technique that can be used to avoid Reflection (the NAME then often doesn't equal the class name, but uses some alias - it can also be used with enums instead of Strings).
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