Java 通过 getComponentType 获取数组对象的元素类型


#Java 反射、泛型与注解#


Class 类的 getComponentType 方法可以获取数组对象的类型。

源码

// 通过 Intellij IDEA 反编译 Class 类的结果

public Class<?> getComponentType() {
    return this.isArray() ? this.componentType : null;
}

示例

@Test
public void test_Long() {
  System.out.println(Long.class.getComponentType());
  // 上面的代码输出 null

  Long[] longArr = new Long[10];
  System.out.println(longArr.getClass().getComponentType());
  // 上面的代码输出 class java.lang.Long

  Long[][] longArrArr = new Long[10][20];
  System.out.println(longArrArr.getClass().getComponentType());
  // 上面的代码输出 class [Ljava.lang.Long;
  System.out.println(longArrArr.getClass().getComponentType().getComponentType());
  // 上面的代码输出 class java.lang.Long
  System.out.println(longArrArr.getClass().getComponentType().getComponentType().getComponentType());
  // 上面的代码输出 null
}


( 本文完 )