我试图通过反射接收字段值。问题是我不知道字段类型,并且在获取值时必须决定它。
I am trying to receive field value via reflection. The problem is I don't know the fields type and have to decide it while getting the value.
此代码会导致以下异常:
This code results with this exception:
无法将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; }还要注意,当你的类继承自另一个类时,你需要递归地确定场。例如,获取给定类的所有字段;
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); } }更多推荐
反射泛型获取字段值
发布评论