简体   繁体   English

通过反射将值设置为java类?

[英]Set value to java class by reflection?

I have this model :我有这个模型:

public class Base_RegisterPlack {


    private String RegisterPlackTypeValue;

    public void setRegisterPlackTypeValue(String registerPlackTypeValue) {
        RegisterPlackTypeValue = registerPlackTypeValue;
    }
}

in this method i pass this object:在这个方法中,我传递了这个对象:

gridView2.setAdapter(GridHelper.getRegisterPlackAdapter(getContext(), getCookie(),
        result_getClsBase_Info.getBase_RegisterPlack()), Base_RegisterPlack.class);

body of setAdapter method is: setAdapter方法的主体是:

public void setAdapter (DataGridAdapter adapter, Class cls) {
    this.baseClass = cls;
    super.setAdapter(adapter);
    setGridAdapter(adapter);
}

Now i want to call set method setRegisterPlackTypeValue so i write this reflection :现在我想调用 set 方法setRegisterPlackTypeValue所以我写了这个反射:

try {
    Field field = baseClass.getDeclaredField("RegisterPlackTypeValue");
    field.setAccessible(true);
    field.set(baseClass,"test");
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

I got this error :我收到此错误:

java.lang.IllegalArgumentException: Expected receiver of type com.module.contracts.Base_RegisterPlack, but got java.lang.Class<com.module.contracts.Base_RegisterPlack>

How can i call set method and convert again this baseClass to the Base_RegisterPlack after set value to it?我如何调用 set 方法并在设置值后再次将此baseClass转换为Base_RegisterPlack

You will need an instance of the class that baseClass represents.您将需要baseClass表示的类的实例。 How to do this exactly will depend on the design of the actual baseClass (ie, whether it has constructors or static factory methods), and what arguments these needs.如何做到这一点将取决于实际baseClass的设计(即,它是否具有构造函数或静态工厂方法),以及这些需要什么参数。 In the simplest case, your base class will have a parameterless constructor, and you can simply do:在最简单的情况下,您的基类将有一个无参数构造函数,您可以简单地执行以下操作:

field.set(baseClass.newInstance(),"test");

However, you will probably want to retain a reference to whatever instance is returned by newInstance .但是,您可能希望保留对newInstance返回的任何实例的引用。

It's important to remember that with reflection an instance of type Field represents a field declaration in its declaring class, and not an actual field (instance variable) in an object.重要的是要记住,通过反射, Field类型的实例表示其声明类中的字段声明,而不是对象中的实际字段(实例变量)。 Thus, the value stored in variable field in your code is not related to any instance.因此,代码中变量field中存储的值与任何实例无关。 This is why when you call Field.set(target, value) you have to supply an object of class baseClass .这就是为什么当您调用Field.set(target, value)您必须提供类baseClass的对象。 The field of that object, which is represented by field , will be set to value "test" .由 field 表示的该对象的field将设置为值"test" See this tutorial for details.有关详细信息,请参阅本教程

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

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