调用MyClass.class和MyClass.getClass()之间有什么区别 [英] What's the difference between calling MyClass.class and MyClass.getClass()

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

问题描述

MyClass.class MyClass.getClass()两者似乎都返回 java .lang.Class 。是否有微妙的区别或可以互换使用?此外, MyClass.class 超类 Class 类的公共属性? (我知道这存在,但似乎无法在javadocs中找到任何提及)

MyClass.class and MyClass.getClass() both seem to return a java.lang.Class. Is there a subtle distinction or can they be used interchangeably? Also, is MyClass.class a public property of the superclass Class class? (I know this exists but can't seem to find any mention of it in the javadocs)

推荐答案

一个是实例方法,所以它返回特定对象的类,另一个是Class常量(即在编译时已知)。

One is an instance method, so it returns the class of the particular object, the other is a Class constant (i.e. known at compile-time).

 Class n = Number.class;
 Number o = 1;
 o.getClass() // returns Integer.class
 o = BigDecimal.ZERO;
 o.getClass();  // returns BigDecimal.class

这两种情况都返回Class对象的实例,它描述了一个特定的Java类。对于同一个类,它们返回相同的实例(每个类只有一个Class对象)。

Both cases return instances of the Class object, which describes a particular Java class. For the same class, they return the same instance (there is only one Class object for every class).

获取Class对象的第三种方法是

A third way to get to the Class objects would be

Class n = Class.forName("java.lang.Number");

请记住,接口也有Class对象(例如上面的数字)。

Keep in mind that interfaces also have Class objects (such as Number above).


另外,MyClass.class是超类Class类的公共属性吗?

Also, is MyClass.class a public property of the superclass Class class?

这是一种语言关键字。

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

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