[英]using primitive type as Generic object
我有一种从数组中检索元素的方法,并且我想对几种原始类型(int [],double [],...)使用相同的方法。 方法如下:
public static int[] getElementsFromTo(int[] data,int from, int to){
int[] selectedData = new int[to-from];
for (int idx = from; idx < to; idx++){
selectedData[idx-from]=data[idx];
}
return selectedData;
}
我看过一些有类似问题的帖子,但找不到很好的答案,或者至少不能理解。 最接近的响应是此线程Java Generic Primitive类型的nd数组 。
一些建议使用Object [],然后在运行时获取原始类型,但我不知道如何。 我猜该方法的签名看起来类似于:
public static Object[] getElementsFromTo(Object[] data,int from, int to)
但是,如何获取数据的类型以使用适当的原始类型实例化selectedElements数组?
非常感谢
您可以实现的最接近的使用以下方法
@SuppressWarnings("unchecked")
public static <A> A copyOf(A array, int from, int to) {
int len = to - from;
A a = (A) Array.newInstance(array.getClass().getComponentType(), len);
System.arraycopy(array, from, a, 0, len);
return a;
}
这将复制原始和非原始数组类型的数组,但是使用反射来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.