黑马程序员技术交流社区

标题: 反射的使用示例 [打印本页]

作者: 池中月    时间: 2015-7-6 11:59
标题: 反射的使用示例
通过java反射机制,可以更加深入的控制程序的运行过程,可以逆向控制程序的执行过程;而这种功能是通过反射对象的构造函数、方法、成员实现的:
示例:
      使用反射扩展数组的长度。
代码:
  1. /*
  2. * 通过反射实现扩张数组长度的方法
  3. */

  4. package unit16;

  5. import java.lang.reflect.*;

  6. public class ReFlexTest2 {

  7.         public static void main(String[] args) {

  8.                 Test test = new Test();

  9.                 test.print();

  10.                 test.is = (int[]) addArrayLength(test.is, 10);
  11.                 test.ss = (String[]) addArrayLength(test.ss, 10);

  12.                 test.print();

  13.         }

  14.         public static Object addArrayLength(Object array, int newLength) {
  15.                 Object newArray = null;
  16.                 Class componentType = array.getClass().getComponentType();//创建反射对象
  17.                 newArray = Array.newInstance(componentType, newLength);//使用指定参数创建一个该类对象
  18.                 System.arraycopy(array, 0, newArray, 0, Array.getLength(array));//通过替换,生成新数组
  19.                 return newArray;
  20.         }
  21. }

  22. class Test {

  23.         public int[] is = { 1, 2, 3 };

  24.         public String[] ss = { "A", "B", "C" };

  25.         public void print() {//遍历数组

  26.                 for (int index = 0; index < is.length; index++) {
  27.                         System.out.println("is[" + index + "]=" + is[index]);
  28.                 }

  29.                 System.out.println();

  30.                 for (int index = 0; index < ss.length; index++) {
  31.                         System.out.println("ss[" + index + "]=" + ss[index]);
  32.                 }

  33.                 System.out.println();

  34.         }

  35. }
复制代码









作者: 加多宝    时间: 2015-7-6 18:23
初学者还真看不懂




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2