反射:在静态方法中获取调用对象 [英] Reflection: get invocation object in static method

查看:53
本文介绍了反射:在静态方法中获取调用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个方法中是否可以得到一个调用静态方法的对象?

我有这个代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆