Andrei Botalov
Andrei Botalov

Reputation: 21096

Reflection: get invocation object in static method

Is it possible to get an object that invoked static method in this method?

I have this code:

class A{
    static void foo(){
    }
}
A a = new A();
a.foo();

Can I get instance a in method foo() ?

Upvotes: 1

Views: 358

Answers (4)

SLaks
SLaks

Reputation: 888303

No; that's what static means.
The compiler actually completely ignores the instance.

Use an instance method.

Upvotes: 0

rascio
rascio

Reputation: 9289

No is impossible...the static method don't have the reference, you have to pass it reimplementing the method as:

class A{
    static void foo(A theObject){
    }
}
A a = new A();
A.foo(a);

and is better don't call the static method from the instance of the object

Upvotes: 0

Tony the Pony
Tony the Pony

Reputation: 41457

By definition, there is no instance object for a static method (static methods do not operate on a specific object, they are defined within a class purely for namespacing) -- so no.

Upvotes: 1

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46425

Firstly, your code isn't good as a programmer.

It is because static methods are class-level methods and should be called without any instance of class.

Recommended approach :

class A{
    static void foo(){
    }
}
A.foo();

Can I get instance a in method foo() ?

Nope, you can't. Because foo() is declared as static. So you can't use this inside that method, since this contains a reference to the object that invoked the method.

Upvotes: 2

Related Questions