为什么getClass()不能作为静态方法使用? [英] Why isn't getClass() available as a static method?
问题描述
在静态上下文中,为什么不能调用静态版本的 getClass()
(而不是必须使用 my.package。 name.MyClassName.class
)?
In static contexts, how come you can't call a static version of getClass()
(rather than having to use my.package.name.MyClassName.class
) ?
编译器是否足够聪明,无法确定何时使用对象方法+何时使用静态方法?
Isn't the compiler smart enough to determine when to use object methods + when to use static methods?
为清晰起见,请注意:
我不是说应该使用 static getClass()
代替非静态方法 getClass()
(这很明显 - 如果 SpecialFoo
是 Foo
的子类,那么 getClass()
Foo
可以返回 Foo.class
或 SpecialFoo.class
或其他东西,必须在运行时确定。
I'm not saying that a static getClass()
should be used instead of the non-static method getClass()
(that's kind of obvious -- if SpecialFoo
is a subclass of Foo
, then the getClass()
of a Foo
could return Foo.class
or SpecialFoo.class
or something else and it has to be determined at runtime).
我说我想知道为什么不存在两个版本的 getClass()
,一个是静态方法,只适用于静态上下文,常规非静态方法 getClass()
。如果不可能,那就不可能了,那就是答案。如果它可能但尚未完成,那么这是一个历史选择,也许这是一个很好的理由。这就是我想知道的。
I'm saying that I'm wondering why aren't there two versions of getClass()
, one that is a static method which only applies in a static context, and the regular non-static method getClass()
. If it's not possible, then it's not possible, and that's the answer. If it's possible but just hasn't been done, then it's a historical choice, and maybe there's a good reason for it. That's what I'd like to know.
宣布
final static Logger logger = LoggerFactory.getLogger(getClass());
而不是
final static Logger logger = LoggerFactory.getLogger(my.package.name.MyClass.class);
前者可以从一个类逐字复制到下一个类,而后者要求你复制每个文件中的类名。
where the former could be copied verbatim from one class to the next, whereas the latter requires you to copy the class name in each file.
推荐答案
如果没有别的,因为同时拥有<$ c $是不合法的c> static 和非 - static
方法的版本(可能因为不鼓励调用 static是合法的
非静态
上下文中的方法。
If nothing else, because it isn't legal to have both a static
and non-static
version of a method (probably because it's legal, if discouraged, to call a static
method in a non-static
context).
我也觉得这样一个方法虽然在定义记录器或其他任何东西的过程中很有用,但在其他上下文中可能会造成混淆,例如从实例方法调用时。
I also feel like such a method, while useful in the context of defining a logger or whatever, could be confusing in other contexts, such as when called from an instance method.
这篇关于为什么getClass()不能作为静态方法使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!