2011-06-02 209 views
4

我有這樣的代碼:Java反射問題

public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType(
      final Class<TypeVO> voClass, final String fieldName) { 
     List<SelectItem> listSelectBox = null; 
     final List<TypeVO> vosList = GenericEjbProxyFactory 
       .getGenericTopValueObjectProxy(voClass) 
       .getAllValueObjects(null); 
     System.out.println("loaded vosList!!!!"); 
     if (vosList != null) { 
      listSelectBox = new ArrayList<SelectItem>(); 
      for (final TypeVO currVo : vosList) { 
       listSelectBox.add(new SelectItem(currVo.getInternalId(), currVo.getName())); 
      } 
     } 
     return listSelectBox; 
    } 

正如你看到這裏,我使用currVo.getName因爲總是currVo有一個名稱屬性。

我希望能夠還使用其他領域,從這個currVo其類型爲voClass,但不是所有currVo類將包含這個字段,所以我不得不使用反射來識別這些getfield命令的方法,是這樣的:

for (final TypeVO currVo : vosList) { 
       for (final Method m : voClass.getMethods()) { 
        if (m.getName().contains(fieldName)) { 
         listSelectBox.add(new SelectItem(
           currVo.getInternalId(), currVo.m)); 
        } 
       } 
      } 

我不知道的是當我找到它時,如何使用該特定方法的值,完全像currVo.getName(因爲當然,currVo.m錯誤)?

例如:如果字段名是 「時代」 我希望把名單:currVo.getAge() ...我只是在這裏封鎖...

回答

3
m.invoke(currVo); 

參見:

還要注意正確的方法來尋找由Nik和Bohemian建議的方法。

+0

'invoke'有兩個參數。 – Mat 2011-06-02 11:33:26

+4

@Mat:它需要vararg作爲第二個參數,它可以是空的。 – axtavt 2011-06-02 11:34:06

+0

啊,正確的JDK> = 1.5。 1.4.2有不同的簽名。 – Mat 2011-06-02 11:39:31

1

您應該使用Method類中的invoke方法。

m.invoke(currVo, (Object[]) null); 

(假設方法沒有參數。)

這將爲JDK的版本1.4的工作以後,由於他們的狀態:

如果由底層所需的正式的參數的數目方法爲0,所提供的參數列表的長度可以爲0 或者null

o該調用的ne參數版本在舊版JVM上不起作用。

+0

這與'm.invoke(currVo,new Object [] {null});'這可能不是你想要的。 – 2011-06-02 11:36:22

+0

我也不同意 - null是一個值,並使對象[]長度1 - 它應該是長度爲零 – Bohemian 2011-06-02 11:44:18

+0

你是對的。 null不是作爲長度爲0或1的數組「投射」到Object []中。 – 2011-06-02 11:48:46

1

我是否正確理解你想調用對象currVo上的方法m?然後,它只是

m.invoke(currVo); 
0

我不知道如果我得到正確的UR的問題,但我的感覺ü問WUD通過下面的代碼來回答:

// Class is whatever is the type u r using 
Method mthd = Class.getMethod("get" + fieldName); //in case method don't have any parameters. 
listSelectBox.add(mthd.invoke(currVo)); 

否則忽略。

1

使用反射來獲得getFieldName方法並調用它,如下所示:

Method method = voClass.getMethod("get" + fieldName); // the getter with no params in the signature 
Object value = method.invoke(currVo}); // invoke with no params 
listSelectBox.add(new SelectItem(currVo.getInternalId(), value)); 

注:這是假設字段名是領導大寫,如「價值」,而不是「價值」,所以前面加上「得到「給出確切的方法名稱,例如」getValue「