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 该怎么修改方法

解决方案 »

  1.   

    Integer num的话,num所指向的值是常量,放在常量池中,无法改变,也就是1无法改变,那么num的值要改变,只有让它指向其他的Integer,但是fun(Integer num)无法完成这个功能。
    所以这是无法完成的
      

  2.   

    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修辞的属性不能更改,所以这里其实是不能随便改的,但是反射是可以做到的