如果我有
public <T> doSomething(T[] array)
{
}
如何从 array
获取 T.class
?
如果我执行 array.getClass()
会得到我的 T[].class
。
最佳答案
组件类型
使用这个:
array.getClass().getComponentType()
Returns the
Class
representing the component type of an array. If this class does not represent an array class this method returnsnull
.
引用:
安全/不安全的类型转换
Is there a way I can cast to Class from Class returned by getComponentType() without getting a compiler warning?
采取这种方法:
public <T> void doSomething(final T[] array) throws Exception{
final Class<? extends Object[]> arrayClass = array.getClass();
final Class<?> componentType = arrayClass.getComponentType();
final T newInstance = (T) componentType.newInstance();
}
这是生成的字节码:
public void doSomething(java.lang.Object[] array) throws java.lang.Exception;
0 aload_1 [array]
1 invokevirtual java.lang.Object.getClass() : java.lang.Class [21]
4 astore_2 [arrayClass]
5 aload_2 [arrayClass]
6 invokevirtual java.lang.Class.getComponentType() : java.lang.Class [25]
9 astore_3 [componentType]
10 aload_3 [componentType]
11 invokevirtual java.lang.Class.newInstance() : java.lang.Object [30]
14 astore 4 [newInstance]
16 return
如您所见,参数类型被删除为Object[],因此编译器无法知道T是什么。是的,编译器可以使用 array.getClass().getComponentType()
,但这有时会失败,因为你可以这样做:
Object[] arr = new String[] { "a", "b", "c" };
Integer[] integerArray = (Integer[]) arr;
doSomething(integerArray);
(在这种情况下 array.getClass().getComponentType()
返回 String.class
,但 T
代表 Integer
。是的,这是合法的,不会产生编译器警告。)
关于java - 获取数组组件的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4737598/