Java如何获取数组的组件类型?
所述Class.getComponentType()方法调用返回Class表示组件式的阵列构成。如果此类不表示数组类,则此方法将返回null引用。
package org.nhooo.example.lang.reflect;
public class ComponentTypeDemo {
public static void main(String[] args) {
String[] words = {"and", "the"};
int[][] matrix = {{1, 1}, {2, 1}};
Double number = 10.0;
Class clazz = words.getClass();
Class cls = matrix.getClass();
Class clz = number.getClass();
//获取数组组件的类型。
Class type = clazz.getComponentType();
System.out.println("Words type: " +
type.getCanonicalName());
//获取数组组件的类型。
Class matrixType = cls.getComponentType();
System.out.println("Matrix type: " +
matrixType.getCanonicalName());
//如果该类不表示它将返回null
//数组。
Class numberType = clz.getComponentType();
if (numberType != null) {
System.out.println("Number type: " +
numberType.getCanonicalName());
} else {
System.out.println(number.getClass().getName() +
" class is not an array");
}
}
}该程序输出以下输出:
Words type: java.lang.String Matrix type: int[] java.lang.Double class is not an array
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西