问题描述
在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()返回 code> a 。如果你有 A a = new B(); 然后 a.getClass ()将返回 B 类。
a.getClass() returns the runtime type of a. I.e., if you have A a = new B(); then a.getClass() will return the B 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.
这篇文章已被重写为。
这篇关于Java中的a.getClass()和A.class之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!