所述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