从一个Serializable对象到另一个Serializable对象的对象值赋值

时间:2013-10-24 11:44:18

标签: java

我有两个对象userBO和userEntity。我想将对象值从userEntity传输到userBO,并且我要求在传输值时不应丢失序列化。这就是我在做的事情。请告诉我这是对的吗?

public static UserBO converUserEntityToUserBO(UserEntity userEntity) {
    UserBO userBO = new UserBO();
    userBO.setUserId(userEntity.getUserId());
    userBO.setUserFile(userEntity.getUserFile());
    userBO.setUserDepartment(userEntity.getUserDepartment());
    return userBO;
}

UserBO.class

public class UserBO implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 3886993061934034729L;

    private int userId;
    private int departmentId;
    private byte[] userFile;
    private String dbAction;

    //getter and setter 
}

UserEntity.class

@Entity
@Table(name="USER_ENTITY")
public class UserEntity implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = -4676281792392490908L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="USER_ID")
    private int userId;

    @Column(name="USER_DEPARTMENT")
    private String userDepartment;

    @Lob()
    @Column(name="USER_FILE")
    private byte[] userFile;

      //getter and setter

}

3 个答案:

答案 0 :(得分:2)

每个可序列化的类都有一个唯一的标识号 它,您已明确指定UserBOUserEntity类:

public class UserBO implements Serializable {
private static final long serialVersionUID = 3886993061934034729L;
...
}
public class UserEntity implements Serializable {
private static final long serialVersionUID = -4676281792392490908L;
...
}

如果未通过声明静态最终长字段明确指定此数字 命名为serialVersionUID,系统通过将复杂的过程应用于类来自动在运行时生成它。

自动生成的值受class’s name, the names of the interfaces it implements, and all of its public and protected members影响。如果以任何方式更改任何这些内容,例如,通过添加新方法,则自动生成的串行版本UID会更改。这将破坏兼容性,并可能在反序列化期间导致意外InvalidClassExceptions

但是在两个类中都声明了一个明确的serialVersionUID值,这保证了不同java编译器实现中的一致serialVersionUID值;因此,在将数据从converUserEntityToUserBO传输到UserEntity时,方法UserBO不会导致任何序列化问题。

答案 1 :(得分:1)

由于您的两个类都具有相同的字段,因此java反射可以更好地帮助您完成。试试这个。

public UserBO loadData (UserEntity userEntity) throws Exception{

    Method[] gettersAndSetters = userEntity.getClass().getMethods();
     UserBO userBO = new UserBO();
    for (int i = 0; i < gettersAndSetters.length; i++) {
            String methodName = gettersAndSetters[i].getName();
            try{
              if(methodName.startsWith("get")){
                 userBO.getClass().getMethod(methodName.replaceFirst("get", "set") ,  
       gettersAndSetters[i].getReturnType() ).invoke(userBO, 
                         gettersAndSetters[i].invoke(userEntity, null));
                    }else if(methodName.startsWith("is") ){
                        userBO.getClass().getMethod(methodName.replaceFirst("is", "set") 
                 ,  gettersAndSetters[i].getReturnType()  ).invoke(userBO, gettersAndSetters[i].invoke(userEntity, null));
                    }

            }catch (NoSuchMethodException e) {

            }catch (IllegalArgumentException e) {

            }

    }

    return null;
}

答案 2 :(得分:0)

你可以用apache bean utils做同样的事情,请参考下面的例子。

**此处,两个DTO中具有相同名称的属性值只会从源复制到taget。

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.builder.ToStringBuilder;

public class BeanUtilsCopyPropertiesTest {

    public static void main(String[] args) {

        FromBean fromBean = new FromBean("fromBean", "fromBeanAProp", "fromBeanBProp");
        ToBean toBean = new ToBean("toBean", "toBeanBProp", "toBeanCProp");

        try {
            System.out.println("Copying properties from fromBean to toBean");
            BeanUtils.copyProperties(toBean, fromBean);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(ToStringBuilder.reflectionToString(fromBean));
        System.out.println(ToStringBuilder.reflectionToString(toBean));
    }

}