Reflection: get invocation object in static method

后端 未结 4 390
轮回少年
轮回少年 2021-01-23 09:38

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         


        
4条回答
  •  半阙折子戏
    2021-01-23 10:18

    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.

提交回复
热议问题