java如何將Object數組轉換為指定類型數組
將Object數組轉換為指定類型數組
1.轉換函數
public static <T> T[] convertArray(Class<T> targetType, Object[] arrayObjects) { if (targetType == null) { return (T[]) arrayObjects; } if (arrayObjects == null) { return null; } T[] targetArray = (T[]) Array.newInstance(targetType, arrayObjects.length); try { System.arraycopy(arrayObjects, 0, targetArray, 0, arrayObjects.length); } catch (ArrayStoreException e) { e.printStackTrace(); } return targetArray; }
2.測試main函數
public static void main(String []args){ GirlVo girlVo =new GirlVo(); girlVo.setGirlId("08123"); girlVo.setGirlName("張一"); GirlVo girlVo2 =new GirlVo(); girlVo2.setGirlId("08456"); girlVo2.setGirlName("張二"); Object[] arrayObjects2 = new Object[2]; arrayObjects2[0] = girlVo; arrayObjects2[1] = girlVo2; GirlVo[] arrayObjects3 ; arrayObjects3 = convertArray(GirlVo.class,arrayObjects2); for(int i=0;i<arrayObjects3.length;i++){ System.out.println("輸出GirlVo: "+arrayObjects3[i].toString()); } }
3.實體類
public class GirlVo implements Serializable { private static final long serialVersionUID = -8545755852948661858L; /**ID號*/ String girlId; /**姓名*/ String girlName; /**年齡*/ long age; /**身高*/ double height; /**罩杯*/ String cupSize; public String getGirlId() { return girlId; } public void setGirlId(String girlId) { this.girlId = girlId; } public String getGirlName() { return girlName; } public void setGirlName(String girlName) { this.girlName = girlName; } public long getAge() { return age; } public void setAge(long age) { this.age = age; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getCupSize() { return cupSize; } public void setCupSize(String cupSize) { this.cupSize = cupSize; } @Override public String toString() { return "GirlVo [girlId=" + girlId +",girlName=" + girlName +",age=" + age +",height=" + height +",cupSize=" + cupSize +"]"; } }
將Object轉換為數組的情況
今天在使用一個別人寫的工具類,這個工具類,主要是判空操作,包括集合、數組、Map等對象是否為空的操作。
下面展示瞭一部分代碼:
public static boolean isEmpty(Object object) { if(object == null){ return true; } //數組判空 if (object.getClass().isArray()) { Object[] obj = (Object[])object; return obj.length == 0; } }
在外部,我傳進來一個數組後,可以看到直接強轉為數組。
我測試瞭下,轉換異常。
後來我自己封裝瞭下,正常的操作應該是這樣的:
public static boolean isEmpty(Object object) { if(object == null){ return true; } //數組判空 if (object.getClass().isArray()) { int len = Array.getLength(object); Object[] obj = new Object[len]; for(int i = 0; i < len; i++) { obj[i] = Array.get(obj, i); } return obj.length == 0; } }
最後測試通過。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。