A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 赵学刚 中级黑马   /  2012-12-2 17:51  /  982 人查看  /  2 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 赵学刚 于 2012-12-3 15:22 编辑

Integer x=4;
x=x+6;  

z通过z.value()进行自动拆箱编程基本数据类型然后把和自动装箱赋给 z对象。
拆箱是对象调用value()方法,那么自动装箱是调用什么方法,或者通过什么机制进行的呢? 求解。。。。。。。。。。谢谢!!!

2 个回复

倒序浏览
1、自动打包与解包



public class IntegerTest
{

public static void main(String[] arg){
  
   Integer a=300000;
  
   Integer b=300000;
  
   Integer c=30;
  
   Integer d=30;
   System.out.println(a.equals(b));
   System.out.println(a==b);   //false
   System.out.println(a==300000);
   
   System.out.println(d.equals(c));
   System.out.println(d==c);
   System.out.println(d==30);
  }
}


将这段代码反编译一下:

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name:   IntegerTest.java

import java.io.PrintStream;

public class IntegerTest
{

    public IntegerTest()
    {
    }

    public static void main(String args[])
    {
        Integer integer = Integer.valueOf(0x493e0);
        Integer integer1 = Integer.valueOf(0x493e0);
        Integer integer2 = Integer.valueOf(30);
        Integer integer3 = Integer.valueOf(30);
        System.out.println(integer.equals(integer1));
        System.out.println(integer == integer1);
        System.out.println(integer.intValue() == 0x493e0);
        System.out.println(integer3.equals(integer2));
        System.out.println(integer3 == integer2);
        System.out.println(integer3.intValue() == 30);
    }
}
发现,其实自动打包就是使用valueOf方法来的,再看看java.lang.Integer中关于valueOf的源代码是怎样的:
public static Integer valueOf(int i) {
  final int offset = 128;
  if (i >= -128 && i <= 127) { // must cache
  return IntegerCache.cache[i + offset];
  }
  return new Integer(i);

}
这下全明白了。

2、其实自动拆包使用的是intValue等类似的方法!

Integer类中使用一个private final int value来保存Integer对象中的int值,所以可以使用反射修改Integer中包含的int值!!!


3、Integer.TYPE与反射

public class ReflectTest {




public static void main(String[] args) {

System.out.println(void.class);//打印出void

System.out.println(Void.TYPE==void.class);//true

System.out.println(Integer.TYPE==Integer.class);//false

System.out.println(Integer.TYPE==int.class);//true




}




}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
嗯  谢谢  虽然好多看不懂,不过大概明白了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马