我有這樣的代碼: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()
...我只是在這裏封鎖...
'invoke'有兩個參數。 – Mat 2011-06-02 11:33:26
@Mat:它需要vararg作爲第二個參數,它可以是空的。 – axtavt 2011-06-02 11:34:06
啊,正確的JDK> = 1.5。 1.4.2有不同的簽名。 – Mat 2011-06-02 11:39:31