利用反射编写泛型数组代码

时间:2021-04-08 12:57:40   收藏:0   阅读:0
public static Object copyOf(Object a,int newLength){
  Class cl = a.getClass();
  if(!cl.isArray()){
      return null;
  }
  Class componentType = cl.getComponentType();
  int length = Array.getLength(a);
  Object newArray = Array.newInstance(componentType,newLength);
  System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
  return newArray;
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!