Java编程:Java的反射机制中的 getComponentType() 方法
轉(zhuǎn)載自??Java編程:Java的反射機制中的 getComponentType() 方法
?
Java 中所有的類都繼承自 Object,數(shù)組本身也是一個 Class,如果我們能夠得到數(shù)據(jù)的 Class 對象,那么我們可以通過反射生成數(shù)組對象。
在Java的反射機制中,通過 數(shù)組的 class 對象的getComponentType()方法可以取得一個數(shù)組的Class對象, 通過Array.newInstance()可以反射生成數(shù)組對象,看示例代碼:
package com.ips.reflect;import java.lang.reflect.Array;public class GetComponentType {public static void main(String [] args){Class<char[]> aa = (Class<char[]>) char.class.getComponentType();System.out.println("the componentType of the char is :" + char.class.getComponentType());System.out.println("the componentType of the char[] is :" + char[].class.getComponentType());System.out.println("the componentType of the String is :" + String.class.getComponentType());System.out.println("the componentType of the String[] is :" + String[].class.getComponentType());System.out.println("the componentType of the int is :" + int.class.getComponentType());System.out.println("the componentType of the int[] is :" + int[].class.getComponentType());System.out.println("the componentType of the Integer is :" + Integer.class.getComponentType());System.out.println("the componentType of the Integer[] is :" + Integer[].class.getComponentType());try {char c = (char)Array.newInstance(char.class.getComponentType(), 10);} catch (Exception e) {e.printStackTrace();}char[] charArray = (char [])Array.newInstance(char[].class.getComponentType(), 100);System.out.println("the length of the charArray is :" + charArray.length);try {String c = (String)Array.newInstance(String.class.getComponentType(), 10);} catch (Exception e) {e.printStackTrace();}String[] strArray = (String [])Array.newInstance(String[].class.getComponentType(), 10);System.out.println("the length of the strArray is :" + strArray.length);} }執(zhí)行結(jié)果:
the componentType of the char is :null?
the componentType of the char[] is :char?
the componentType of the String is :null?
the componentType of the String[] is :class java.lang.String?
the componentType of the int is :null?
the componentType of the int[] is :int?
the componentType of the Integer is :null?
the componentType of the Integer[] is :class java.lang.Integer?
java.lang.NullPointerException?
at java.lang.reflect.Array.newArray(Native Method)?
at java.lang.reflect.Array.newInstance(Array.java:70)?
at com.ips.reflect.GetComponentType.main(GetComponentType.java:23)?
the length of the charArray is :100?
java.lang.NullPointerException?
at java.lang.reflect.Array.newArray(Native Method)?
at java.lang.reflect.Array.newInstance(Array.java:70)?
at com.ips.reflect.GetComponentType.main(GetComponentType.java:31)?
the length of the strArray is :10
通過以上代碼我們可以發(fā)現(xiàn):
?
總結(jié)
以上是生活随笔為你收集整理的Java编程:Java的反射机制中的 getComponentType() 方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软测试 Win11 新版 Outloo
- 下一篇: Java synchronized 中的