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?
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);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다