反射:在静态方法中获取调用对象 [英] Reflection: get invocation object in static method
问题描述
在这个方法中是否可以得到一个调用静态方法的对象?
我有这个代码:
class A{静态无效 foo(){}}A a = new A();a.foo();
我可以在方法 foo()
中获取实例 a
吗?
首先,你的代码不适合程序员.
这是因为静态方法是类级别的方法,应该在没有任何类实例的情况下调用.
推荐方法:
class A{静态无效 foo(){}}A.foo();
<块引用>
我可以在方法 foo() 中获取实例 a 吗?
不,你不能.因为 foo() 被声明作为静态.因此您不能在该方法中使用 this,因为它包含对调用该方法的对象的引用.
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()
?
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.
这篇关于反射:在静态方法中获取调用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!