反射通用获取字段值

编程入门 行业动态 更新时间:2024-10-26 10:39:34
本文介绍了反射通用获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试通过反射获取字段的值.问题是我不知道字段的类型,必须在获取值时决定它.

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); } }

更多推荐

反射通用获取字段值

本文发布于:2023-07-09 14:29:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1086994.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!