Java 反射 Array動態創建數組


Java 反射 Array動態創建數組

@author ixenos

注:java.lang.reflect.Array 是個反射工具包,全是靜態方法,創建數組以多維數組為基准,一維數組只是特殊實現

 

 

 

 創建一個具有指定的組件類型和長度的新數組(一維數組)


newInstance

public static Object newInstance(Class<?> componentType,
                                 int length)
                          throws NegativeArraySizeException
創建一個具有指定的組件類型和長度的新數組。調用此方法等效於創建如下數組:
 int[] x = {length}; //創建數組以多維數組為基准,一維數組只是特殊實現
 Array.newInstance(componentType, x);

 

參數:
componentType - 表示新數組的組件類型的 Class 對象
length - 新數組的長度
返回:
新數組
拋出:
NullPointerException - 如果指定的 componentType 參數為 null
IllegalArgumentException - 如果 componentType 為 Void.TYPE
NegativeArraySizeException - 如果指定的 length 為負

 

 

創建一個具有指定的組件類型和維度的新數組(多維數組)


newInstance

public static Object newInstance(Class<?> componentType,
                                 int... dimensions)
                          throws IllegalArgumentException,
                                 NegativeArraySizeException
創建一個具有指定的組件類型和維度的新數組。
如果 componentType 表示一個非數組類或接口,則新數組具有 dimensions.length 維度,並且將 componentType 作為其組件類型。
如果 componentType 表示一個數組類,則新數組的維數等於 dimensions.lengthcomponentType 的維數的總和。在這種情況下,新數組的組件類型為 componentType 的組件類型。

新數組的維數不能超過該實現所支持的數組維數(通常為 255)

 

參數:
componentType - 表示新數組的組件類型的 Class 對象
dimensions - 表示新數組維度的 int 數組
返回:
新數組
拋出:
NullPointerException - 如果指定的 componentType 參數為 null
IllegalArgumentException - 如果指定的 dimensions 參數是一個零維度的數組,或者所請求的維數超過了該實現所支持的數組維數的限制(通常為 225),或者度的數組,或者所請求的維數超過了該實現所支持的數組維數的限制(通常為 225),或者 componentType 為 Void.TYPE
NegativeArraySizeException - 如果指定的 dimensions 參數中的任意組件為負。   

  創建多維數組示例:

  //get(Object array, int index)   返回指定數組對象中索引組件的值

  //setInt(Object array, int index, int i) 將指定數組對象中索引組件的值設置為指定的 int 值。

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM