I have two classes defined like this:
class A {
public static String getName(){
Class c = getCalledClass();
return c.getSimpleName();
}
}
class B extends A {
//no methods are defined here!
}
I want to know if it is possible to compose the static method getCalledClass() such that calling A.getName() will return A and B.getName() will return B?
Thanks.
1 Answer. Simply try TheClassName. class instead of getClass().
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name.
Static methods can't refer to non-static variables or methods. Static methods can't refer to “super” or “this” members.
The @staticmethod is a built-in decorator that defines a static method in the class in Python. A static method doesn't receive any reference argument whether it is called by an instance of a class or by the class itself.
This is not possible, at least not in the general sense that you've asked.
There is no method B.getName(). While you can type that in code, it will be compiled to identical bytecode to A.getName() (and I think you get a compiler warning too).
Thus at runtime, there is no way to tell how someone referenced the static method - just as there's no way to tell what local variable names a caller is using.
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