Java examples on java.lang.reflect
- How do I invoke a method using Method class?
- How do I get field of a class object and set or get its value?
- How do I get fields of a class object?
- How do I get the methods of a class object?
- How do I create object using Constructor object?
- How do I determine if a class object represents an array class?
- How do I get constructors of a class object?
- How do I get modifiers of a class object?
- How do I get information regarding class name?
- How do I get the component type of an array?
- How do I get direct superclass and interfaces of a class?
- How do I check if a class represent a primitive type?
- How do I check if a class represent an interface type?
How do I get the component type of an array?
The Class.getComponentType() method call returns the Class representing the component type of an array. If this class does not represent an array class this method returns null reference instead.
package org.kodejava.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();
//
// Gets the type of an array component.
//
Class type = clazz.getComponentType();
System.out.println("Words type: " +
type.getCanonicalName());
//
// Gets the type of an array component.
//
Class matrixType = cls.getComponentType();
System.out.println("Matrix type: " +
matrixType.getCanonicalName());
//
// It will return null if the class doesn't represent
// an array.
//
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");
}
}
}
This program print the following output:
Words type: java.lang.String Matrix type: int[] java.lang.Double class is not an array