Thursday, January 05, 2006

Reflection of Generic Array expanding

(1) Traditionally, arrycopy is used to expande array.

static Object[] badWay (Object[] a)
{
int length = a.length * 11/ 10 + 10;
Object[] newA = new Object[length];
System.arrayCopy(a,0,newA,0,a.length);
return newA;

}

it return Object[] only without type info.

However, Array reflection API does it return Object

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

No comments: