Java 中的 a.getClass() 和 A.class 有什么区别? [英] What is the difference between a.getClass() and A.class in Java?

查看:31
本文介绍了Java 中的 a.getClass() 和 A.class 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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 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.

这篇文章已被改写为文章这里.

This post has been rewritten as an article here.

这篇关于Java 中的 a.getClass() 和 A.class 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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