Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: get the called class name from static method

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.

like image 956
bennyl Avatar asked Jul 05 '13 11:07

bennyl


People also ask

How can we get getClass in static method?

1 Answer. Simply try TheClassName. class instead of getClass().

Can we call static method with class name?

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.

Can static method refer to this or super?

Static methods can't refer to non-static variables or methods. Static methods can't refer to “super” or “this” members.

What is @staticmethod?

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.


1 Answers

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.

like image 58
Andrzej Doyle Avatar answered Oct 18 '22 05:10

Andrzej Doyle