java反射问题
我有以下代码:java反射问题,java,Java,我有以下代码: public static final <TypeVO extends BaseVo> List<SelectItem> populateSelectBoxForType( final Class<TypeVO> voClass, final String fieldName) { List<SelectItem> listSelectBox = null; final Lis
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.m是错误的)
例如:如果fieldName是“Age”,我想把它放在列表中:currVo.getAge()。。。我只是被封锁在这里
m.invoke(currVo);
另请参见:
请注意Nik和Bohemian建议的查找方法的正确方法。您应该使用类中的invoke
方法
(假设该方法不带任何参数。)
这适用于JDK 1.4及更高版本,因为它们声明:
如果基础方法所需的形式参数数量为0,则提供的args数组的长度可能为0或null
该调用的单参数版本在较旧的JVM上不起作用。我是否正确理解您希望在对象currVo
上调用方法m
?那就简单了
m.invoke(currVo);
我不确定我是否正确回答了你的问题,但我觉得你所问的问题可以通过以下代码来回答:
// 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));
否则忽略。使用反射获取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));
注意:这假设fieldName是大写的,例如“Value”,而不是“Value”,因此在它前面加上“get”会给出确切的方法名,例如“getValue”invoke
接受两个参数。@Mat:它接受vararg作为第二个参数,它可以是空的。感谢新的签名提示-没有意识到反射已经变了varargst这与m.invoke(currVo,newobject[]{null})相同代码>这可能不是您想要的。我也不同意-null是一个值,使对象[]长度为1-它应该是零长度-您是对的。null是“强制转换”到Object[]
的,而不是作为长度为0或1的数组。不过,我有点不对劲,对Object[]
的显式强制转换对于编译它来说是必要的,至少在1.6版上没有警告。
// 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));
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));