使用java反射设置值

时间:2011-07-24 03:00:12

标签: java reflection

提前感谢您的时间和帮助。查看了其他帖子,但只提供了一些信息,所以如果有人给出完整的图片,那就非常感激了。

我有:

public enum AddressType {
HOME,WORK,BILLING,SHIPPING,OTHER
}

public class AddressDto implements java.io.Serializable {

private String street;
private String city;
private String stateCode;
private int zipcode;
private String country;
private AddressType addressType;

public AddressDto() {
}

public String getStreet() {
    return street;
}

public void setStreet(String street) {
    this.street = street;
}

public String getCity() {
    return city;
}

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

public String getStateCode() {
    return stateCode;
}

public void setStateCode(String stateCode) {
    this.stateCode = stateCode;
}

public int getZipcode() {
    return zipcode;
}

public void setZipcode(int zipcode) {
    this.zipcode = zipcode;
}

public String getCountry() {
    return country;
}

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

public AddressType getAddressType() {
    return addressType;
}

public void setAddressType(AddressType addressType) {
    this.addressType = addressType;
}
}

@Entity
@Table(name = "ADDRESS")
public class Address implements java.io.Serializable {

private String street;
private String city;
private String stateCode;
private int zipcode;
private String country;
private AddressType addressType;

public Address() {
}

public String getStreet() {
    return street;
}

public void setStreet(String street) {
    this.street = street;
}

public String getCity() {
    return city;
}

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

public String getStateCode() {
    return stateCode;
}

public void setStateCode(String stateCode) {
    this.stateCode = stateCode;
}

public int getZipcode() {
    return zipcode;
}

public void setZipcode(int zipcode) {
    this.zipcode = zipcode;
}

public String getCountry() {
    return country;
}

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

public AddressType getAddressType() {
    return addressType;
}

public void setAddressType(AddressType addressType) {
    this.addressType = addressType;
}
}

使用反射,我试图从DTO获取值并将值设置为实体。为何反思?认为我可以将这个反射代码重新用于涉及DTO和实体的所有其他类似情况。

请建议有效的方法。

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用Apache BeanUtils来执行此操作。班级BeanUtils有适当的方法。