vendredi 8 février 2019

Java - set the field value to the correct type from string(reflection)

I have class like this:

public enum  Type {
    ONE, TWO
}

@Data
public class Car {
    private String name;
    private int year;
    private Type type;
}

I have new object:

Car car = new Car();

And I have this data:

Map<String, String> data....

name - BMW
year - 2018
type - TWO

key and value - String

And I need set this values to object(except for reflection, I see no ways)

    Field year = car.getClass().getDeclaredField("year");
    year.setAccessible(true);
    year.set(car, data.get("year"));//2018 as string

I get exception(differently and could not be I know):

Caused by: java.lang.IllegalArgumentException: Can not set int field com.example.mapper.Car.year to java.lang.String

Therefore, the question is - how do I correctly cast the value to the desired type to set in the field?

This is a simple example, because the real task is very long explained. If in short - I get a list of values (they are always a string) and the names of the fields in which they change (also a string) and must update the fields of the object with new values





Aucun commentaire:

Enregistrer un commentaire