哪个类调用了我的静态方法? [英] Which class invoked my static method?

查看:36
本文介绍了哪个类调用了我的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有静态方法的 Java 类,如下所示:

<前>A级{静态无效 foo(){//哪个类调用了我?}}

进一步假设类 A 有任意数量的子类:

<前>B 类扩展 A { }C 类扩展了 A { }D 类扩展 A { }...

现在考虑以下方法调用:

<前>A.foo();B.foo();C.foo();D.foo();...

我的问题是,方法 foo() 如何知道哪个类正在调用它?

解决方案

它不能,这是静态方法问题的一部分.就编译器而言,A.foo()B.foo() 是完全一样的东西.事实上,它们编译成相同的字节码.没有比这更相似的了.

如果您确实需要此类信息,请使用单例并将 foo() 转换为实例方法.如果你仍然喜欢静态语法,你可以构建一个门面 A.foo().

Suppose that I have a Java class with a static method, like so:

class A
{
    static void foo()
    {
        // Which class invoked me?
    }
}

And suppose further that class A has an arbitrary number of subclasses:

class B extends A { }
class C extends A { }
class D extends A { }
...

Now consider the following method invocations:

A.foo();
B.foo();
C.foo();
D.foo();
...

My question is, how can method foo() tell which class is invoking it?

解决方案

It can't, and that's part of the problem with static methods. As far as the compiler is concerned A.foo() and B.foo() are exactly the same thing. In fact, they compile down to the same bytecode. You can't get more similar than that.

If you really need this sort of information, use a singleton and turn foo() into an instance method. If you still like the static syntax, you can build a facade A.foo().

这篇关于哪个类调用了我的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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