import java.lang.reflect.Array;
public class TestArray {
public static void main(String[] args) {
String [] strs = new String[]{"c","p","x"};
//如果此类是数组,则返回表示此类组件类型的 Class
Class<?> st = strs.getClass().getComponentType();
//打印数组的定义类型
System.out.println("数组类型:"+st.getName());
//数组的长度
System.out.println("数组的长度:"+Array.getLength(strs));
//指定位置索引数组值
System.out.println(Array.get(strs, 2));
//重新设置指定索引处元素的值
Array.set(strs, 2, "xx");
System.out.println(Array.get(strs, 2));
System.out.println("------------------------");
//构建新的数组
int [] ints = new int[]{1,2,3};
Class<?> intarray = ints.getClass().getComponentType();
//构建和intarray同类型的数组,第二个为数组的长度
int[] newArray = (int[]) Array.newInstance(intarray,5);
/*
*数组的copy,第一个参数为源数组,第二个为从源数组第几个
*元素开始copy,第三个参数为目标数组,第四个参数为目标数组起始位置,
*第五个参数为结束位置
*/
System.arraycopy(ints, 0, newArray, 0,Array.getLength(ints));
Class<?> newints = newArray.getClass().getComponentType();
//打印新数组
int length = Array.getLength(newArray);
for(int i =0;i<length;i++){
System.out.println(Array.get(newArray, i));
}
}
}
利用反射对数组进行操作
最新推荐文章于 2020-08-05 22:03:30 发布