Java 中的 a.getClass() 和 A.class 有什么区别? [英] What is the difference between a.getClass() and A.class in Java?
问题描述
在 Java 中,选择使用 a.getClass()
或 A.class
有哪些优缺点?两者都可以在需要 Class>
的任何地方使用,但我想在不同情况下使用两者会带来性能或其他微妙的好处(就像 Class.forName()
和 ClassLoader.loadClass()
.
In Java what pros/cons exist surrounding the choice to use a.getClass()
or A.class
? Either can be used wherever a Class<?>
is expected, but I imagine that there would be performance or other subtle benefits to using both in different circumstances (just like there are with Class.forName()
and ClassLoader.loadClass()
.
推荐答案
我不会比较它们的优缺点,因为它们有不同的目的,而且两者之间很少有选择".
I wouldn't compare them in terms of pros/cons since they have different purposes and there's seldom a "choice" to make between the two.
a.getClass()
返回a
的运行时类型.即,如果你有A a = new B();
那么a.getClass()
将返回B
类.
a.getClass()
returns the runtime type ofa
. I.e., if you haveA a = new B();
thena.getClass()
will return theB
class.
A.class
静态计算为 A
类,并用于通常与反射相关的其他目的.
A.class
evaluates to the A
class statically, and is used for other purposes often related to reflection.
在性能方面,可能存在可衡量的差异,但我不会对此发表任何评论,因为最终它取决于 JVM 和/或编译器.
In terms of performance, there may be a measurable difference, but I won't say anything about it because in the end it is JVM and/or compiler dependent.
这篇文章已被改写为文章这里.
This post has been rewritten as an article here.
这篇关于Java 中的 a.getClass() 和 A.class 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!