MyException - 我的异常网
当前位置:我的异常网» J2SE » 运用反射编扩展数组,运行结果总是出错

运用反射编扩展数组,运行结果总是出错

www.MyException.Cn  网友分享于:2013-12-24  浏览:2次
使用反射编扩展数组,运行结果总是出错
今天在自学反射内容时, 编写了下面一个程序;用于扩展任意数组;无论我怎样修改结果总是
int[14] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
请各路高手在闲暇时帮忙分析一下,万分感谢
//
import java.lang.reflect.Array;

public class ArrayGrowTest {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4 };
a = (int[]) goodArrayGrow(a);
arrayPrint(a);
}

public static Object goodArrayGrow(Object o) {
Class cl = o.getClass();
if (!cl.isArray())
return null;
int length = Array.getLength(o);
int newLength = length * 11 / 10 + 10;
Class componentType = cl.getComponentType();
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(newArray, 0, o, 0, length);
return newArray;
}

public static void arrayPrint(Object o) {
Class cl = o.getClass();
if (!cl.isArray())
return;
Class componentType = cl.getComponentType();
int length = Array.getLength(o);
System.out.print(componentType.getName() + "[" + length + "] = {");
for (int i = 0; i < length; i++) {
if (i > 0)
System.out.print(", ");
System.out.print(Array.get(o, i));
}
System.out.println("}");
}
}


------解决方案--------------------
System.arraycopy(o, 0, newArray, 0, length);
------解决方案--------------------
探讨
System.arraycopy(o, 0, newArray, 0, length);

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有