简体   繁体   中英

Java reflection in two level of objects

Suppose I have two classes.

public class User {
    private String userName;
    private String age;
    private Address address;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}

public class Address {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

I want to set city and country of user using java reflection. parameter map looks like

address.city=COLOMBO 
address.country=SRI LANKA.

what is the best way to access address properties inside user object using java reflection.

Since I am going to create object through CSV. So when user send attribute with dot (.) its means its object inside another object.

I want to write global reflection method to use through out the application. One method to create object using CSV

The best way would be to create a new Address object, and then call the setters for this object and finally call the setAddress for the user.

The best pattern of use doesn't change because you are using reflection. I suggest you do the same thing but using reflection.

I think using reflection for that is not the best way. Anyway, as Peter tell you in the first answer, you should create a new object and assign it using the setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM