Java中的类 getComponentType() 方法和示例
Java.lang.Class 类的getComponentType()方法用于获取表示数组的组件类型的Class,如果该类代表一个。否则返回 null。
句法:
public Class getComponentType()
参数:此方法不接受任何参数。
返回值:如果该类表示一个,则该方法返回表示数组的组件类型的类。否则返回 null。
下面的程序演示了 getComponentType() 方法。
示例 1:
Java
// Java program to demonstrate getComponentType() method
import java.util.*;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the type of interfaces of myClass
// using getComponentType() method
System.out.println("ComponentType of myClass: "
+ myClass.getComponentType());
}
}
Java
// Java program to demonstrate getComponentType() method
import java.util.*;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
int[] Arr = new int[5];
// returns the Class object
Class arrClass = Arr.getClass();
// Get the ComponentType of arrClass
// using getComponentType() method
System.out.println("ComponentType of myClass: "
+ arrClass.getComponentType());
}
}
输出:
Class represented by myClass: class Test
ComponentType of myClass: null
示例 2:
Java
// Java program to demonstrate getComponentType() method
import java.util.*;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
int[] Arr = new int[5];
// returns the Class object
Class arrClass = Arr.getClass();
// Get the ComponentType of arrClass
// using getComponentType() method
System.out.println("ComponentType of myClass: "
+ arrClass.getComponentType());
}
}
输出:
ComponentType of myClass: int
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getComponentType–