[英]Java generic array from null generic type
Consider the Array.newInstance static method as a way of creating a generic type array in Java. 将Array.newInstance静态方法视为在Java中创建通用类型数组的一种方式。 What I'm failing to see how to do is create a generic array from a null generic type argument: 我看不到怎么做是从一个空的通用类型参数创建通用数组:
/**
* Creates and fills a generic array with the given item
*/
public static <T> T[] create(T item, int length)
{
T[] result = (T[]) Array.newInstance(item.getClass(), length);
for(int i = 0; i < length; i++)
result[i] = item;
return result;
}
The above works when I call eg create("abc", 10); 当我调用例如create(“ abc”,10);时,以上方法有效 I'm getting a String[] of length 10 with "abc" in all positions of the array. 我在数组的所有位置都得到了一个长度为10的String [],其中带有“ abc”。 But how could I make a null string argument return a String array of length 10 and null in all positions? 但是,如何使null字符串参数返回长度为10且在所有位置都为null的String数组?
eg 例如
String nullStr = null;
String[] array = create(nullStr, 10); // boom! NullPointerException
Is there perhaps a way to get the class of "item" without using one of its members (as it's null)? 也许有一种方法可以在不使用成员之一的情况下获取“ item”类(因为它为null)?
I know I can just new up an array String[] array = new String[10] , but that's not the point. 我知道我可以新建一个数组String [] array = new String [10] ,但这不是重点。
Thanks 谢谢
Maybe this is useful. 也许这很有用。
public static <T> T[] create(Class<T> clazz, int length)
{
T[] result = (T[]) Array.newInstance(clazz, length);
return result;
}
As you point out, you can't call: 如您所指出,您不能致电:
create(null, 10)
because your code can't determine the type (it ends up calling null.getClass()
=> NPE). 因为您的代码无法确定类型(它最终会调用null.getClass()
=> NPE)。
You could pass the class separately: 您可以单独通过课程:
public static <T> T[] create(Class<T> type, int length, T fillValue)
{
T[] result = (T[]) Array.newInstance(type, length);
for(int i = 0; i < length; i++)
result[i] = fillValue;
return result;
}
// Some optional convenience signatures:
public static <T> T[] create(Class<T> type, int length) {
return create(type, length, null);
}
public static <T> T[] create(T fillValue, int length) {
if (fillValue == null) {
throw new IllegalArgumentException("fillValue cannot be null");
}
return create(fillValue.getClass(), length, fillValue);
}
public static void main(String[] args) {
String[] a = create(String.class, 10, null);
}
Well, why not change the method to take a Class object instead, and just directly pass in String.class
? 好吧,为什么不将方法改为采用Class对象,而直接将其传递给String.class
呢? Java can't get the class type of null
because it has no class type! Java无法获得null
的类类型,因为它没有类类型! Any object can be null. 任何对象都可以为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.