java - 获取数组组件的类

标签 java arrays generics

如果我有

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 returns null.

引用:


安全/不安全的类型转换

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/

相关文章:

java - 如何实例化 Kafka Connect Schema 数组

javascript - 对或错 : Declaring array and calling function on same line, javaScript

C# 泛型类型参数跨类共享

java - 错误: The type T cannot be used in GenericTypeMatcher - Expression expected

java - 检查Set中是否存在java对象

java - 安卓工作室 : ExpandableListView and EditText

java-如何打印 "()"内数组的重复数字

python - 使用对象 dtype 的 ndarray 与 None 进行元素比较

java - 使用传递的泛型进行 GSON 反序列化

java - 如何在java中将通用对象添加到列表中?