反射通用获取字段值 [英] Reflection generic get field value
问题描述
我正在尝试通过反射获取字段的值.问题是我不知道字段的类型,必须在获取值时决定它.
I am trying to obtain a field's value via reflection. The problem is I don't know the field's type and have to decide it while getting the value.
此代码导致此异常:
无法将 java.lang.String 字段 com....fieldName 设置为 java.lang.String
Can not set java.lang.String field com....fieldName to java.lang.String
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
我尝试投射,但出现编译错误:
I tried to cast, but I get compilation errors:
field.get((targetType)objectValue)
或
targetType objectValue = targetType.newInstance();
我该怎么做?
推荐答案
像之前回答的一样,你应该使用:
Like answered before, you should use:
Object value = field.get(objectInstance);
另一种有时更受欢迎的方法是动态调用 getter.示例代码:
Another way, which is sometimes prefered, is calling the getter dynamically. example code:
public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
还要注意,当你的类从另一个类继承时,你需要递归地确定Field.例如,获取给定类的所有字段;
Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;
for (Class<?> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
这篇关于反射通用获取字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!