Suppose that I have a Java class with a static method, like so:
class A { static void foo() { // Which class invoked me? } }
And suppose further that class A has an arbitrary number of subclasses:
class B extends A { } class C extends A { } class D extends A { } ...
Now consider the following method invocations:
A.foo(); B.foo(); C.foo(); D.foo(); ...
My question is, how can method foo() tell which class is invoking it?
It can’t, and that’s part of the problem with static methods. As far as the compiler is concerned
A.foo()andB.foo()are exactly the same thing. In fact, they compile down to the same bytecode. You can’t get more similar than that.If you really need this sort of information, use a singleton and turn
foo()into an instance method. If you still like the static syntax, you can build a facadeA.foo().