0
点赞
收藏
分享

微信扫一扫

不使用第三方交换俩个数据的值-利用反射

岛上码农 2022-05-17 阅读 39


public static void main(String[] args) {
int x = 10, y = 20; //定义两个变量
System.out.println("交换前 x=" + x + ",y=" + y);
swap(x, y);
System.out.println("交换前 x=" + x + ",y=" + y);
}

private static void swap(Integer a, Integer b) {
int temp = a;
try {
Class clazz = a.getClass();
Field value = clazz.getDeclaredField("value");
value.setAccessible(true);
value.setInt(a, b);

value.setInt(b, temp);
} catch (Exception ex) {
ex.printStackTrace();
}
}



举报

相关推荐

0 条评论