"int" 的类对象和 Integer.class

2017-04-27 12:57:56 +08:00
 esolve

Class<integer> c1 = int.class

这里给人的感觉是 int.class 是 Integer 类对象 但是 System.out.print(int.class)的结果却是 int 怎么理解?

1328 次点击
所在节点    问与答
6 条回复
momocraft
2017-04-27 13:01:55 +08:00
这是 Java?

int.class 是 Class<Integer> 或 Class<?> 对象

print 出的"int" 来自 https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#toString()
starvedcat
2017-04-27 13:19:55 +08:00
这个问题我不太懂,但是我也想参与一下讨论

我觉得,int.class 是 Integer 类对象,但它的值是“ int ”,所以楼主说的两者并不矛盾
tianshuang
2017-04-27 14:11:58 +08:00
首先这个语句是编译有错的,如果泛型中是 Integer 则能编译通过。int.class 是原语的类对象,Integer.class 是包装类的类对象。
tianshuang
2017-04-27 14:19:08 +08:00
可以参考 Integer 类的源码:
/**
* The {@code Class} instance representing the primitive type
* {@code int}.
*
* @since JDK1.1
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

以下代码将打印出 true。
Class<Integer> c1 = int.class;
System.out.println(c1 == Integer.TYPE);
tianshuang
2017-04-27 14:26:48 +08:00
原语的类对象不等于包装类的类对象,以下代码将打印 false。
Class<Integer> c1 = int.class;
System.out.println(c1 == Integer.class);
SoloCompany
2017-04-27 22:25:02 +08:00
楼主的代码是可以编译通过的(忽略拼错成小写的 Integer 的问题)

的确 int 和 Intege 是两个完全不相容的类型,但在 jdk 的泛型化定义里面,所有 primative type 的 representing Class instance 的泛参类型就是其所对应的 wrapper class (泛参类型不可以是 primative type)

int.class / Integer.TYPE / Class.getPrimitiveClass("int ”) 都是同一个实例

而且看 java.lang.Integer 的源码,有很清楚的定义

/**
* The {@code Class} instance representing the primitive type
* {@code int}.
*
* @since JDK1.1
*/
@SuppressWarnings("unchecked")
public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");


而且这几个 primitive type 所对应的 class instance 有些很有意思的特性
可以试运行一下以下这段代码:

https://gist.github.com/lwr/666d1a4ce985810ce3318cbe1ad76fb0

(要让它能跑起来,还需要实现两个很简单的方法)

我们还可以发现最后一个比较有意思的 primitive type: void <-> Void

虽然 void 不代表任何内容, 但在语言层面还是给它留下了两个 class 实例

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/357691

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX