欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用反射创建一个数组

程序员文章站 2022-05-28 18:03:21
...
import java.lang.reflect.Array;
import java.util.Random;

public class CreateArrayWithReflection {

	/**
	 * @param args
	 * @author Bruce
	 * @since 1.0, 08/19/11
	 */
	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);
		}
	}

}
相关标签: 反射 数组