1

I have an array with field names - fieldNamesArr and array with values for those fields - fieldValuesArr. Also I have Object obj,created form class Class using .newInstanse();.

How can I set appropriate fields in obj using this two arrays?
(we're assuming that obj has all of this fields and they are public)

Class ourClass = Definer.getClassByName(tmpStrArr[1]);
obj = ourClass.newInstance();

List<String> fieldNamesArr = new ArrayList<>();
List<String> fieldValuesArr = new ArrayList<>();

[remark 1] Supposed that obj doesn't have a complex fields (just primitive types)

1
  • If I simply paste the question title into Google I get lots of results. Have you tried anything? Commented Apr 10, 2016 at 19:52

1 Answer 1

1

I just found a solution. It should look something like that, I guess:

int i=0;        
for (String tmpStr: fieldNamesArr) {
   Field field = ourClass.getField(tmpStr);   

   //converting string from fieldValuesArr[i] to required type //   

   field.set(obj,value);
   i++
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.