V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
esolve
V2EX  ›  问与答

"int" 的类对象和 Integer.class

  •  
  •   esolve · 2017-04-27 12:57:56 +08:00 · 1327 次点击
    这是一个创建于 2549 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Class<integer> c1 = int.class

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

    6 条回复    2017-04-27 22:25:02 +08:00
    momocraft
        1
    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
        2
    starvedcat  
       2017-04-27 13:19:55 +08:00
    这个问题我不太懂,但是我也想参与一下讨论

    我觉得,int.class 是 Integer 类对象,但它的值是“ int ”,所以楼主说的两者并不矛盾
    tianshuang
        3
    tianshuang  
       2017-04-27 14:11:58 +08:00
    首先这个语句是编译有错的,如果泛型中是 Integer 则能编译通过。int.class 是原语的类对象,Integer.class 是包装类的类对象。
    tianshuang
        4
    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
        5
    tianshuang  
       2017-04-27 14:26:48 +08:00
    原语的类对象不等于包装类的类对象,以下代码将打印 false。
    Class<Integer> c1 = int.class;
    System.out.println(c1 == Integer.class);
    SoloCompany
        6
    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 实例
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2823 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:30 · PVG 19:30 · LAX 04:30 · JFK 07:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.