Java generic array from null generic type
Consider the Array.newInstance static method as a way of creating a generic type array in 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.getCl开发者_JS百科ass(), length);
for(int i = 0; i < length; i++)
result[i] = item;
return result;
}
The above works when I call e.g. create("abc", 10); I'm getting a String[] of length 10 with "abc" in all positions of the array. But how could I make a null string argument return a String array of length 10 and null in all positions?
e.g.
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)?
I know I can just new up an array String[] array = new String[10], but that's not the point.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).
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
? Java can't get the class type of null
because it has no class type! Any object can be null.
精彩评论