一些开发人员通过创建Object[]
并转换为泛型类型来创建泛型类型的数组,如以下示例代码所示:
public class ArrTest<E> {
public void test(E a){
E[] b = (E[])new Object[1];
b[0] = a;
System.out.println(b[0]);
}
public static void main(String[] args){
ArrTest<String> t = new ArrTest<String>();
t.test("Hello World");
}
}
该示例将起作用,只是发出警告:Type safety: Unchecked cast from Object[] to E[]
。
气馁吗?这是创建泛型类型数组的最佳方法吗?如果我在我的软件中广泛使用此对象,这会导致意外结果或异常吗?
答案 0 :(得分:3)
在问题的示例中,b
变量不是String[]
,即使我们将其转换为E[]
并定义E
为String
,同时构建实例。这是一个Object[]
。发生这种情况是因为Java不知道运行时类型E
是什么,因为在此示例中,我们没有为E
定义父类。因此,它会自动将Object
作为其父级。
换句话说,public class ArrTest<E>
与public class ArrTest<E extends Object>
相同。
Java不知道E
在运行时是什么,因为它是unchecked
。 Unchecked
表示Java不会检查E
类型是否是已定义父类的扩展或实现。因此,Java在运行时唯一知道的E
是<E extends Object>
。
因此
E[] b = (E[]) new Object[1];
将以
执行 Object[] b = (Object[]) new Object[1];
这就是为什么该示例不会抛出ClassCastException
并且会使开发人员感到困惑。
如果我们尝试将b
用作真实String[]
,那么Java将抛出ClassCastException
,因为Java将其视为Object[]
。例如,如果我们将方法更改为:
public E[] test(E a){
E[] b = (E[])new Object[1];
b[0] = a;
System.out.println(b[0]);
return b;
}
public static void main(String[] args){
ArrTest<String> t = new ArrTest<String>();
String[] result = t.test("Hello World");
}
现在我们将在ClassCastException
收到String[] result
,因为返回的类型为Object[]
,我们正在尝试将其存储在String[]
变量中。 Java将看到类型差异并抛出异常。
这就是为什么不鼓励将Object[]
强制转换为通用数组,这只会导致混淆。
在写这个答案之前,我创建了一个测试用例,其中有一些可能的方法来创建一个通用数组,我得出结论,这是最好的方法:
public class ExampleType<A extends Number>{
public <T extends A> T[] bestMethod(T[] array)
{
if(array.length < testSize)
array = (T[]) Array.newInstance(array.getClass().getComponentType(), testSize); //Type safety: Unchecked cast from Object to T[]
System.out.println("in this case: "+array.getClass().getComponentType().getSimpleName());
return array;
}
}
保证返回与作为参数传递的数组相同类型的数组,并且它必须是A
中定义的ExampleType<A extends Number>
实例。如果您创建ExampleType
Integer
,则需要使用Integer[]
作为参数。如果您不想特定数组Integer
,但想要存储任何类型的数字,可以使用Number[]
作为参数。
如果您不需要类中的泛型类型,可以将其简化为:
public <T> T[] bestMethod(T[] array)
如果您希望它仅返回Number
的子类:
public <T extends Number> T[] bestMethod(T[] array)
如果你想自己测试一下,这是我的测试用例:
public class Test {
public static class ArrTest<E>
{
public void test(E a){
E[] b = (E[])new Object[1];
b[0] = a;
System.out.println(b[0]);
}
public E[] test2(E a){
E[] b = (E[])new Object[1];
b[0] = a;
System.out.println(b[0]+" "+b.getClass().getComponentType());
return b;
}
public static void main(String[] args){
ArrTest<String> t = new ArrTest<String>();
t.test("Hello World");
try{String[] result = t.test2("Hello World");}catch(Exception e){System.out.println(e);}
}
}
public static void main(String[] args) {
ArrTest.main(args);
System.out.println("#############\nWe want an array that stores only integers, sampledata: 1, samplearray: Integer");
test(new ExampleType<Integer>(Integer.class), 1, new Integer[0], new Integer[10]);
System.out.println("#############\nWe want an array that stores any type of Number, sampledata: 2L, samplearray: Number");
test(new ExampleType<Number>(Number.class), 2L, new Number[0], new Number[10]);
System.out.println("#############\nWe want an array that stores any type of CustomNumberA, sampledata: CustomB(3L), samplearray: CustomNumberA");
test(new ExampleType<CustomNumberA>(CustomNumberA.class), new CustomNumberB(3L), new CustomNumberA[0], new CustomNumberA[10]);
System.out.println("#############\nWe want A to be any type of number but we want to create an array of CustomNumberA, sampledata: CustomB(3L), samplearray: CustomNumberA");
test(new ExampleType<Number>(Number.class), new CustomNumberB(3L), new CustomNumberA[0], new CustomNumberA[10]);
}
public static <A extends Number> void test(ExampleType<A> testType, A sampleData, A[] smallSampleArray, A[] bigSampleArray)
{
Class<A> clazz = testType.clazz;
System.out.println("#############\nStarting tests with ExampleType<"+clazz.getSimpleName()+">");
System.out.println("============\nCreating with badMethod()...");
A[] array;
try
{
array = testType.badMethod();
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
System.out.println("============\nCreating with alsoBadMethod("+sampleData+" ["+sampleData.getClass().getSimpleName()+"])...");
try
{
array = testType.alsoBadMethod(sampleData);
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
System.out.println("============\nCreating with nearlyGoodMethod("+smallSampleArray.getClass().getSimpleName()+" len: "+smallSampleArray.length+")...");
try
{
array = testType.nearlyGoodMethod(smallSampleArray);
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
System.out.println("============\nCreating with nearlyGoodMethod("+bigSampleArray.getClass().getSimpleName()+" len: "+bigSampleArray.length+")...");
try
{
array = testType.nearlyGoodMethod(bigSampleArray);
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
System.out.println("============\nCreating with bestMethod("+smallSampleArray.getClass().getSimpleName()+" len: "+smallSampleArray.length+")...");
try
{
array = testType.bestMethod(smallSampleArray);
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
System.out.println("============\nCreating with bestMethod("+bigSampleArray.getClass().getSimpleName()+" len: "+bigSampleArray.length+")...");
try
{
array = testType.bestMethod(bigSampleArray);
testType.executeTests(array);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
}
@RequiredArgsConstructor @ToString()
public static class CustomNumberA extends Number{
@Delegate final Long n;
}
public static class CustomNumberB extends CustomNumberA{
public CustomNumberB(Long n) { super(n); }
}
@RequiredArgsConstructor
public static class ExampleType<A>{
private int testSize = 7;
final Class<A> clazz;
public A[] badMethod()
{
System.out.println("This will throw a ClassCastException when trying to return the array because Object is not a type of "+clazz.getSimpleName());
A[] array = (A[]) new Object[testSize]; //Warning: Type safety: Unchecked cast from Object[] to A[]
System.out.println("Array of "+array.getClass().getComponentType()+" created");
return array;
}
public A[] alsoBadMethod(A sampleType)
{
System.out.println("Will not respect A type ("+clazz.getSimpleName()+"), will always use the highest type in sampleType and tell that it's A[] but it's not, in this case will return "+sampleType.getClass().getSimpleName()+"[] and said it was "+clazz.getSimpleName()+"[] while developing");
A[] array = (A[]) Array.newInstance(sampleType.getClass(), testSize); //Type safety: Unchecked cast from Object to A[]
return array;
}
public A[] nearlyGoodMethod(A[] array)
{
System.out.println("The only guarantee is that the returned array will be of something that extends A ("+clazz.getSimpleName()+") so the returned type is not clear, may be of A or of the type passed in the argument but will tell it's A[] but may not be");
if(array.length < testSize)
array = (A[]) Array.newInstance(array.getClass().getComponentType(), testSize); //Type safety: Unchecked cast from Object to A[]
System.out.println("in this case: "+array.getClass().getComponentType().getSimpleName()+"[], expecting: "+clazz.getSimpleName()+"[]");
return array;
}
public <T extends A> T[] bestMethod(T[] array)
{
System.out.println("It's guaranteed to return on array of the same type as the sample array and it must be an instance of A, so, this is the best method");
if(array.length < testSize)
array = (T[]) Array.newInstance(array.getClass().getComponentType(), testSize); //Type safety: Unchecked cast from Object to T[]
System.out.println("in this case: "+array.getClass().getComponentType().getSimpleName()+"[], expecting: "+array.getClass().getComponentType().getSimpleName()+"[]");
return array;
}
public void executeTests(A[] array)
{
tryToSet(array, 0, 1);
tryToSet(array, 1, 2L);
tryToSet(array, 2, 3.1);
tryToSet(array, 3, 4F);
tryToSet(array, 4, (byte)0x5);
tryToSet(array, 5, new CustomNumberA(6L));
tryToSet(array, 6, new CustomNumberB(7L));
}
public void tryToSet(A[] array, int index, Object value)
{
System.out.println("Trying to set "+value+" ("+value.getClass().getSimpleName()+") at "+index+" in a array of "+array.getClass().getComponentType().getSimpleName());
try
{
if(array instanceof Object[]) ((Object[]) array)[index] = value;
else array[index] = (A) value; //Type safety: Unchecked cast from Object to A
System.out.println("## OK: Success: "+array.getClass().getComponentType().getSimpleName()+"["+index+"] = "+array[index]);
}
catch(Exception e){ System.out.println(">> ERR: "+e); }
}
}
}
以下是测试结果......您可以看到bestMethod
始终返回预期结果。
答案 1 :(得分:2)
您的警告只是指出编译器无法根据Java语言规范指定的规则确保静态类型安全。换句话说,它注意到静态类型安全已被破坏。
但这并不能使这个成语毫不含糊地气馁。以下是来自JDK itself(格雷码格式)的完全合法案例:
323 @SuppressWarnings("unchecked")
324 public <T> T[] toArray(T[] a) {
325 if (a.length < size)
326 // Make a new array of a's runtime type, but my contents:
327 return (T[]) Arrays.copyOf(elementData, size, a.getClass());
328 System.arraycopy(elementData, 0, a, 0, size);
329 if (a.length > size)
330 a[size] = null;
331 return a;
332 }
虽然未经检查使用了向下转换,但更高级别的逻辑表明它是类型安全的。