反射泛型获取字段值 [英] Reflection generic get field value

查看:1141
本文介绍了反射泛型获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过反射接收字段值。问题是我不知道字段类型,并且在获取值时必须决定它。

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

这篇关于反射泛型获取字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆