There is a class

public class A { public Integer field; } 

As in runtime, assign to the field the value of a string of the type given to the desired type:

 A a = new A(); String field = "field"; String value = "123"; a.getClass().getField(field).set(a, /*value*/ ); // КАК?! 
  • Why keep it in line? - Qwertiy
  • @Qwertiy is api, what can you do - gwgw
  • @post_zeew yes, but for any type of field it is necessary to bring to the desired type of field (at least for simple types) - gwgw
  • The decision with switch as field suits? - post_zeew
  • @post_zeew otherwise? - gwgw

2 answers 2

It can be like this

 A a = new A(); String fieldName = "field"; String fieldValue = "123"; // берем поле Field field = a.getClass().getDeclaredField(fieldName); // берем класс поля Class fieldType = field.getType(); // ищем конструктор с параметром типа String Constructor constructor = fieldType.getDeclaredConstructor(String.class); // делаем новый объект Object value = constructor.newInstance(fieldValue); field.set(a, value); System.out.println(a.field); 
  • It may not be clear from the question, but why should I use reflection if I know the type of the field? The field can be of any type, i.e. Need to bring in rantayme - gwgw
  • absolutely any? and always converted from string? - Mikhail Vaysman
  • always out of line. It is possible only for those who have the necessary parse type wrappers for primitive types at least - gwgw
  • @gwgw I changed the code. For most wrappers will work. - Mikhail Vaysman

Judging by this question and one of the answers to it:

if

some good way to find is unlikely to work.

The most primitive decision:

 A a = new A(); String field = "field"; String value = "123"; Field targetField = a.getClass().getField(field); String targetFieldType = targetField.getType().getSimpleName(); switch (targetFieldType) { case "Integer": case "int": targetField.set(a, Integer.parseInt(value)); break; case "String": targetField.set(a, value); break; } 
  • this is sad, in vain tormented me, thanks - gwgw