2013-04-24 118 views
0

創建我創建了一個實例我的POJO類像下面的使用反射設定值:反思 - 如何對POJO類,它的實例使用反射

package com.hexgen.tools; 

public class Foo { 

    public static void main(String[] args) { 
     Class c = null; 
     try { 
      c = Class.forName("com.hexgen.ro.request.CreateRequisitionRO"); 
      Object o = c.newInstance(); 
      System.out.println(o.toString()); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException iae) { 
      iae.printStackTrace(); 
     } catch (InstantiationException ie) { 
      ie.printStackTrace(); 
     } 
    } 
} 

當我印我得到了下面的字符串:

[email protected][transSrlNo=<null>,transCode=<null>,inflowOutflow=<null>,transDate=<null>,tradeDate=<null>,tradeDateUpto=<null>,tradeTime=<null>,investCategory=<null>,custodian=<null>,holdType=<null>,securityType=<null>,security=<null>,assetClass=<null>,issuer=<null>,fundManager=<null>,marketType=<null>,tradePriceType=<null>,requisitionType=<null>,priceFrom=<null>,priceTo=<null>,marketPrice=<null>,averagePrice=<null>,quantity=<null>,price=<null>,grossAmtTcy=<null>,exchRate=<null>,grossAmtPcy=<null>,grossIntTcy=<null>,grossIntPcy=<null>,netAmountTcy=<null>,netAmountPcy=<null>,acquCostTcy=<null>,acquCostPcy=<null>,yieldType=<null>,purchaseYield=<null>,marketYield=<null>,ytm=<null>,mduration=<null>,currPerNav=<null>,desiredPerNav=<null>,currHolding=<null>,noofDays=<null>,realGlPcy=<null>,realGlTcy=<null>,nowLater=<null>,isAllocable=false,acquCostReval=<null>,acquCostHisTcy=<null>,acquCostHisPcy=<null>,exIntTcy=<null>,exIntPcy=<null>,accrIntReval=<null>,accrIntTcy=<null>,accrIntPcy=<null>,grossAodTcy=<null>,grossAodPcy=<null>,grossAodReval=<null>,bankAccAmtAcy=<null>,bankAccAmtPcy=<null>,taxAmountTcy=<null>,unrelAmortTcy=<null>,unrelAmortPcy=<null>,unrelGlTcy=<null>,unrelGlPcy=<null>,realGlHisTcy=<null>,realGlHisPcy=<null>,tradeFeesTcy=<null>,tradeFeesPcy=<null>,investReason=<null>,settleDate=<null>,stkSettleDate=<null>,custodianN=<null>,portfolio=<null>,userId=<null>]

字面上所有的值都設置爲null,我想在同類產品中制定者設置的值。由於setters名稱可以隨時更改,我計劃動態設置值,以便沒有發生靜態值設置。

是否可以爲新創建的實例動態設置值?就像創建一些枚舉並在枚舉中有一些默認值一樣,如果它是字符串設置了某些默認值,如果int設置了一些默認值,如下所示。

how to do this also i created a object which is not a array if i want to create array of objects using reflection how to go about it? 

好心幫我找出並修復這些..

回答

2

根據定義,POJO沒有標準制定者。我懷疑你的意思是JavaBean。

要使用一個JavaBean的setter方法,最簡單的方法是使用Introspector

public class Main { 
    public static void main(String... ignored) throws Exception { 
     SimpleBean sb = new SimpleBean(); 

     BeanInfo info = Introspector.getBeanInfo(SimpleBean.class); 
     System.out.println("Calling setters"); 
     for (PropertyDescriptor pd : info.getPropertyDescriptors()) { 
      if (pd.getWriteMethod() == null) continue; 
      System.out.println("\tSetting " + pd.getName()); 
      pd.getWriteMethod().invoke(sb, "Set now"); 
     } 
     System.out.println("Reading the getters"); 
     for (PropertyDescriptor pd : info.getPropertyDescriptors()) { 
      System.out.println("\t" + pd.getName() + " = " + pd.getReadMethod().invoke(sb)); 
     } 
    } 


    public static class SimpleBean { 
     String text; 
     String words; 

     public String getText() { 
      return text; 
     } 

     public void setText(String text) { 
      this.text = text; 
     } 

     public String getWords() { 
      return words; 
     } 

     public void setWords(String words) { 
      this.words = words; 
     } 
    } 
} 

打印

Calling setters 
    Setting text 
    Setting words 
Reading the getters 
    class = class Main$SimpleBean 
    text = Set now 
    words = Set now 
2

您可以使用類對象定義的字段:

Field f = c.getFields()[0]; //or getField("...") 
f.set(o, "new value"); 

編輯:如果你想只使用setter方法:

for(Method m : c.getMethods()) 
    if (m.getName().startsWith("set") && m.getParameterTypes().length == 1) 
    m.invoke(o, "myValue"); 
+1

感謝WRM,我的情況II正在試圖爲該類創建實例,並設置可用屬性的值。是否有可能相應地找到屬性類型和設置值,例如爲具有默認值的每種類型枚舉並設置它們。也如何使用反射來創建對象數組?請不要誤會並幫助我 – 2013-04-24 10:32:18

+0

這是什麼'm.getParameterTypes()。length == 1'的含義? – 2013-04-24 10:35:23

+0

,以確保此方法只接受1個參數,而不是更少或更多 – wrm 2013-04-24 10:59:57