Reflection: get invocation object in static method

狂风中的少年 提交于 2019-12-31 03:53:28

问题


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() ?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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

Use an instance method.



来源:https://stackoverflow.com/questions/6667115/reflection-get-invocation-object-in-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!