这个在转换的过程中会调用Integer的静态方法valueOf()方法。
源码如下:
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
这里有个IntegerCache其实就是在VM启动时,为了加快int类型到Integer的转化速度,在VM启动时就new出一些int类型与Integer的对应关系,方便直接返回Integer,而不用new。new其实是很耗时的。
注意:
这里的valueOf是static的。因为,这时你想要的是Integer对象,所以只能是static的。
这个需要调用Integer的方法intValue()。这个方法不是静态的。
源码如下:
/**
* Returns the value of this {@code Integer} as an
* {@code int}.
*/
public int intValue() {
return value;
}
这样,当Integer转成int时,如果Integer是null的,则可能会抛空指针异常NullPointerException。
Integer integer = 1;
int i = integer;
首先会调用Integer的静态方法valueOf,然后调用integer对象的intValue方法。这时,如果integer对象是null的,在integer.intValue()时,会出现NullPointerException。
javac Test.java
javap -verbose Test
public class Test {
public static void main(String[] args) {
Integer integer = 1;
int i = integer;
System.out.println(i);
}
}
看先反编译代码:
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=3, args_size=1
0: iconst_1
1: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: aload_1
6: invokevirtual #3 // Method java/lang/Integer.intValue:()I
9: istore_2
10: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream;
13: iload_2
14: invokevirtual #5 // Method java/io/PrintStream.println:(I)V
17: return
一个是invokestatic、一个是invokevirtual。
如果Integer integer = null;的话:
public class Test {
public static void main(String[] args) {
Integer integer = null;
int i = integer;
System.out.println(i);
}
}
反编译后:
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=3, args_size=1
0: aconst_null
1: astore_1
2: aload_1
3: invokevirtual #2 // Method java/lang/Integer.intValue:()I
6: istore_2
7: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream;
10: iload_2
11: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
14: return
因篇幅问题不能全部显示,请点此查看更多更全内容