2011-06-02 122 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“