简体   繁体   中英

how to fill a composite object using java reflection?

I have a config file like this:

Provider Search,ConfigURL,http://myUrl

I want to fill this object using reflection

public class MyPrefrences {

    public ProviderSearch ProviderSearch;
}



    public class ProviderSearch {

        public String ConfigURL;

    }

here is my code, but I fail to set the composite object:

    MyPrefrences myPrefrences = new MyPrefrences();

    try {
        Field field = myPrefrences.getClass().getDeclaredField(normalizedCategory);
        Field field2 = field.getClass().getDeclaredField(normalizedKey);
        field2.set(field, val);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

how would you do it

a) if all leaves members are String?

b) if I the leaves can be primitives and non-primitives?

The providerSearch must not be null in myPreference's instance.

MyPrefrences myPrefrences = new MyPrefrences();

try {
    Field field = MyPrefrences.class.getDeclaredField("ProviderSearch");
    Field field2 = ProviderSearch.class.getDeclaredField("ConfigURL");

    field2.set(field.get(myPrefrences), val);
} catch (Exception ex) {
    throw new RuntimeException(ex);
}

In addition, I recommend:

  • Don't use public field.
  • Use variables that begin with lower case.
  • Use getters and setters.

First of all You need to pass your Object reference which value you want set in field.set() .

And second: field.getClass() gives you java.lang.reflect.Field , use field.getType() to get Class you need. So, it should be like this

Field field1=myPref.getClass().getDeclaredField("ProviderSearch");
Object obj=field1.getType().newInstance();
Field field2=field1.getType().getDeclaredField("ConfigURL");
field2.set(obj, "www.stackoverflow.com");
field1.set(myPref, obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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