I have class
public class Car {
private String name;
private int year;
public Car(String name, int year) {
this.name = name;
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
Person Class
public class Person {
private String name;
private int age;
private boolean adult;
private Car car;
public Person(String name, int age, final Car car) {
this.name = name;
this.age = age;
this.car = car;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", adult=" + adult +
'}';
}
}
I have to get fields using reflection and set / get values dynamically.
I am keeping them in a map
Map<String, Field> map = new HashMap<>();
for (Field field : Person.class.getDeclaredFields()) {
field.setAccessible(true);
map.put(field.getName(), field);
}
System.out.println(map);
I have the map now with all the fields later on I can get/set any attribute
What I cannot get it how do I store Car in the map like
"car.name" , <FIELD>
"car.age" , <FIELD>
later on I can get from map like mapp.get("car.name", person) that would return the car name
Aucun commentaire:
Enregistrer un commentaire