当前位置: 代码迷 >> J2SE >> 大神 一个和引用 ,包装类有关的有关问题
  详细解决方案

大神 一个和引用 ,包装类有关的有关问题

热度:396   发布时间:2016-04-23 21:27:13.0
大神请指教 一个和引用 ,包装类有关的问题
public class Test {

public static void main(String[] args) {
Integer num = new Integer(1);
System.out.println(num);
fun(num);
System.out.println(num);
}

public static void fun(Integer num){
num.valueOf(3);
}


这里两次输出的都是1 我想在调用方法后输出3 该怎么修改方法

------解决方案--------------------
Integer num的话,num所指向的值是常量,放在常量池中,无法改变,也就是1无法改变,那么num的值要改变,只有让它指向其他的Integer,但是fun(Integer num)无法完成这个功能。
所以这是无法完成的
------解决方案--------------------
import java.lang.reflect.Field;

public class Test2 {

public static void main(String[] args) {
Integer num = new Integer(1);
System.out.println(num);
fun(num);
System.out.println(num);
}

public static void fun(Integer num) {
Class clazz = num.getClass();
try {
Field field = clazz.getDeclaredField("value");
field.setAccessible(true);
field.set(num, 3);
field.setAccessible(false);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

}

看Integer的源码
private final int value;
value是被final修辞的,被final修辞的属性不能更改,所以这里其实是不能随便改的,但是反射是可以做到的
  相关解决方案