简体   繁体   English

如何通过反射将字段值设置为纯对象

[英]How to set a Field value as a plain Object via Reflection

I have a model class: 我有一个模型课:

public class Model {

@KeyDefinition("name")
private String mName;

@KeyDefinition("age")
private int mAge;

public Model(){

}

And I have a List<Object> (Values) & a List<String> (Keys) that I handle through the map method: 我有一个List<Object> (值)和List<String> (键),我可以通过map方法进行处理:

public <T> T map(Class<T> cls){
    T instance;
    try {
        instance = cls.newInstance();
        for(Field field: cls.getDeclaredFields()){
            if(field.isAnnotationPresent(KeyDefinition.class)){
                KeyDefinition annotation = field.getAnnotation(KeyDefinition.class);
                for(int i = 0; i < mKeys.size(); i++){
                    if(annotation.value().equals(mKeys.get(i))){
                        field.setAccessible(true);
                        field.set(instance, mValues.get(i));
                    }
                }
            }
        }
    } catch (InstantiationException | IllegalAccessException e) {
        System.out.println(e.getMessage());
        return null;
    }
    return instance;
}

So if the value of the annotations is equals to a "Key" item from a list, then I grab the Object in the corresponding position and set the field's value to that. 因此,如果注释的值等于列表中的“键”项,那么我将Object抓住在相应的位置并将字段的值设置为该值。

But, when I reaches the mAge field I get the following message: 但是,当我到达mAge字段时,会收到以下消息:

java.lang.IllegalArgumentException: Can not set int field Model.mAge to java.lang.String
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeIntegerFieldAccessorImpl.set(UnsafeIntegerFieldAccessorImpl.java:98)

What I have possibly done wrong? 我做错了什么?

The error is pretty clear. 错误非常明显。 Age is an int and you're trying to assign an Object to it through reflection. 年龄是一个整数,并且您正在尝试通过反射为其分配对象。 It's unsafe because the Object could be anything. 这是不安全的,因为对象可以是任何东西。 You'll either need to a) determine the field type in your loop and convert Objects to whatever type accordingly, or b) give yourself a setter that can accept an Object, and go through setters rather than fields, or c) make the age field be a generic Object, which of course is not ideal. 您要么需要a)确定循环中的字段类型,然后将Objects转换为相应的类型,要么b)给自己一个可以接受Object的setter,并通过setter而不是字段进行操作,或者c)设定年龄字段是通用对象,这当然不是理想的。

Another strategy you could use is to make some object to whatever converter class and specify it as a parameter to your annotation, then use that to convert. 您可以使用的另一种策略是使某个对象成为任何转换器类,并将其指定为注释的参数,然后使用该对象进行转换。

Sorry about lack of examples, on phone. 很抱歉在电话上缺少示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM