基本数据类型中值引用的简单demo

xiaoxiao2021-02-27  373

import java.lang.reflect.Field; public class TestYinYong { public static void main(String[] args) { Integer a = 1,b=2; System.out.println("a = "+a); System.out.println("b = "+b); //swap1(a,b); swap2(a,b); System.out.println("a = "+a); System.out.println("b = "+b); } private static void swap1(Integer a, Integer b) { Integer tmp = a; a = b; b = tmp; } private static void swap2(Integer c, Integer d) { try { Field field = Integer.class.getDeclaredField("value"); //将override设置成true,可以修改final修饰的Integer的属性 field.setAccessible(true); Integer tmp = new Integer(c); field.set(c, d.intValue()); field.set(d, tmp); } catch (Exception e) { e.printStackTrace(); } } }
转载请注明原文地址: https://www.6miu.com/read-4180.html

最新回复(0)