Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which class invoked my static method?

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?

like image 825
Slumberthud Avatar asked Nov 12 '08 03:11

Slumberthud


People also ask

How static method is invoked?

Invoking a public static Method After we have the class instance, we can get the public static method object by calling the getMethod method. Once we hold the method object, we can invoke it simply by calling the invoke method.

Are static methods invoked on objects?

A static method is not part of the objects it creates but is part of a class definition. Unlike instance methods, a static method is referenced by the class name and can be invoked without creating an object of class.

Can we call static method using 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.

How do you identify a static method?

A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class.

Can a static method be invoked by an object of a class?

The static method cannot invoke the instance member as well as methods of the class. Because static methods are accessed without the object reference of the class but we cannot access the instance variables and method without an object reference.

What is the difference between @staticmethod and Classmethod?

@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It's definition is immutable via inheritance. @classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance.


1 Answers

It can't, and that's part of the problem with static methods. As far as the compiler is concerned A.foo() and B.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 facade A.foo().

like image 137
Daniel Spiewak Avatar answered Sep 21 '22 16:09

Daniel Spiewak