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
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短