题: 定义两个 Integer 对象传递给一个方法, 方法执行后两个 Integer 的值需要互相转换
public static void practise(MyConsumer<Integer> consumer) {
Integer value1 = 1;
Integer value2 = 2;
System.out.println("start: value1=" + value1 + ", value2=" + value2);
consumer.accept(value1, value2);
System.out.println("end: value1=" + value1 + ", value2=" + value2);
}
@FunctionalInterface
public interface MyConsumer<T> {
void accept (T value1, T value2);
}
编程方式一: 传值与传引用的区别
practise((value1, value2) -> {
Integer temp = value1;
value1 = value2;
value2 = temp;
return;
});
输入结果:
start: value1=1, value2=2
end: value1=1, value2=2
编程方式二: Integer 在 -127 ~ 128 之间的缓存
practise((value1, value2) -> {
try {
Field declaredField = Integer.class.getDeclaredField("value");
declaredField.setAccessible(true);
Integer intValue = value1.intValue();
declaredField.set(value1, value2);
declaredField.set(value2, intValue);
} catch (Exception e) {}
return;
});
输出结果:
start: value1=1, value2=2
end: value1=2, value2=2
编程方式三: 清空缓存
practise((value1, value2) -> {
try {
Field declaredField = Integer.class.getDeclaredField("value");
declaredField.setAccessible(true);
Integer intValue = new Integer(value1.intValue());
declaredField.set(value1, value2);
declaredField.set(value2, intValue);
} catch (Exception e) {}
return;
});
输出结果:
start: value1=1, value2=2
end: value1=2, value2=1