一道编程题目

落日映苍穹つ 2022-05-08 11:33 324阅读 0赞

昨天在微信群看到有人在讨论一个问题,
具体题目如下:
入参两个Intger,返回空,然后使这个两个值在调用函数后交换。打印交换后的值,比如你初始化两个变量a和b对应的值分别是3,4那么通过调用方法,传入这两个参数,然后再次打印,a和b的值应该就是4和3而不在是3,4.
在Java中我们都知道是值传递,所以刚看到题目时,你可能觉得没有值返回,怎么可以实现?其实我们可以利用反射的思想来进行修改对象的值,最后再打印对象的值。
具体的实现如下:

  1. import java.lang.reflect.Field;
  2. public class SwapTwoNumber {
  3. public static void main(String[] args) {
  4. Integer num1 = 3;
  5. Integer num2 = 4;
  6. System.out.println("交换前:");
  7. System.out.println("num1 = :" + num1 + " ===== " + "num2 = : "+ num2);
  8. swapTwoIntegerNoReturn(num1,num2);
  9. System.out.println("交换后:");
  10. System.out.println("num1 = :" + num1 + " ===== " + "num2 = : "+ num2);
  11. }
  12. /**
  13. * 入参两个Intger,返回空,然后使这个两个值在调用函数后交换
  14. * @param num1
  15. * @param num2
  16. */
  17. private static void swapTwoIntegerNoReturn(Integer num1, Integer num2) {
  18. try {
  19. //通过反射获取Integer对象中的私有域value
  20. Field field = Integer.class.getDeclaredField("value");
  21. field.setAccessible(true);
  22. int temp = num1.intValue();
  23. //调用set(obj,value)方法,obj表示要修改的对象,value 表示要给修改对象赋予的值
  24. field.set(num1, num2);
  25. field.set(num2, new Integer(temp));
  26. } catch (NoSuchFieldException e) {
  27. e.printStackTrace();
  28. } catch (SecurityException e) {
  29. e.printStackTrace();
  30. } catch (IllegalArgumentException e) {
  31. e.printStackTrace();
  32. } catch (IllegalAccessException e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }

关于上述代码中我和需要使用value属性和set方法,你可以看看源码。
Integer的源码中有这样一段代码:

  1. /**
  2. * The value of the {@code Integer}.
  3. *
  4. * @serial
  5. */
  6. private final int value;

此处的私有域value表示的应该是Integer对象的值,所以需要使用value属性。
再看一下package java.lang.reflect.Field类中的set方法:

  1. /**
  2. * Sets the field represented by this {@code Field} object on the
  3. * specified object argument to the specified new value. The new
  4. * value is automatically unwrapped if the underlying field has a
  5. * primitive type.
  6. * @param obj the object whose field should be modified
  7. * @param value the new value for the field of {@code obj}
  8. * being modified
  9. */
  10. @CallerSensitive
  11. public void set(Object obj, Object value)
  12. throws IllegalArgumentException, IllegalAccessException
  13. {
  14. if (!override) {
  15. if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
  16. checkAccess(Reflection.getCallerClass(), clazz, obj, modifiers);
  17. }
  18. }
  19. getFieldAccessor(obj).set(obj, value);
  20. }

通过上面的部分源码,我们可以参数来set方法的第一个参数obj代表对象需要修改的域。value表示需要修改的域的新值来替换原有的值。

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,324人围观)

还没有评论,来说两句吧...

相关阅读

    相关 一道编程题目

    昨天在微信群看到有人在讨论一个问题, 具体题目如下: 入参两个Intger,返回空,然后使这个两个值在调用函数后交换。打印交换后的值,比如你初始化两个变量a和b对应的值