博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java 数组反射例子

Posted on 2006-12-07 14:23  daniel-shen  阅读(1823)  评论(0编辑  收藏  举报

清单 2-3. 使用反射检查数组类型和长度
public class ArrayReflection {
  public static void main (String args[]) {
    printType(args);
  }
  private static void printType (Object object) {
    Class type = object.getClass();
    if (type.isArray()) {
      Class elementType = type.getComponentType();
      System.out.println("Array of: " + elementType);
      System.out.println(" Length: " + Array.getLength(object));
    }
  }
}

运行时创建数组:
int array[] = (int[])Array.newInstance(int.class, 5);

int dimensions[] = {5};
int array[] = (int[])Array.newInstance(int.class, dimensions);

int dimensions[] = {3, 4};
int array[][] = (int[][])Array.newInstance(int.class, dimensions);

int dimensions[] = {5,4,3,2,1};
int array[][][][][] = (int[][][][][])Array.newInstance(int.class, dimensions);



清单 2-4. 使用反射创建、填充和显示数组


            import java.lang.reflect.Array;
            import java.util.Random;
            public class ArrayCreate {
            public static void main (String args[]) {
            Object array = Array.newInstance(int.class, 3);
            printType(array);
            fillArray(array);
            displayArray(array);
            }
            private static void printType (Object object) {
            Class type = object.getClass();
            if (type.isArray()) {
            Class elementType = type.getComponentType();
            System.out.println("Array of: " + elementType);
            System.out.println("Array size: " + Array.getLength(object));
            }
            }
            private static void fillArray(Object array) {
            int length = Array.getLength(array);
            Random generator = new Random(System.currentTimeMillis());
            for (int i=0; i<length; i++) {
            int random = generator.nextInt();
            Array.setInt(array, i, random);
            }
            }
            private static void displayArray(Object array) {
            int length = Array.getLength(array);
            for (int i=0; i<length; i++) {
            int value = Array.getInt(array, i);
            System.out.println("Position: " + i +", value: " + value);
            }
            }
            }
            

运行时,输出将如下所示(尽管随机数会不同):


            Array of: int
            Array size: 3
            Position: 0, value: -54541791
            Position: 1, value: -972349058
            Position: 2, value: 1224789416