测试结构
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SuperClass {
private long id;
private String name;
}
@Data
@ToString(callSuper = true)
public class SubClass extends SuperClass {
}
转换
- 1)直接转换
public class TestMain {
public static void main(String[] args) {
SuperClass superClass = new SuperClass(1, "name");
SubClass subClass = (SubClass) superClass;
System.out.println(subClass);
}
}
出现如下异常:
Exception in thread "main" java.lang.ClassCastException: org.company.cast.SuperClass cannot be cast to org.company.cast.SubClass
at org.company.TestMain.main(TestMain.java:9)
- 2)序列化反序列化
需引入
Jackson
依赖,可参考 Jackson 使用简介 。
public class TestMain {
public static void main(String[] args) {
SuperClass superClass = new SuperClass(1, "name");
String serialize = serialize(superClass);
SubClass subClass = deserialize(serialize, SubClass.class);
System.out.println(subClass);
}
private static final ObjectMapper objectMapper = new ObjectMapper();
@SneakyThrows
public static String serialize(Object obj) {
return objectMapper.writeValueAsString(obj);
}
@SneakyThrows
public static <T> T deserialize(String json, Class<T> clazz) {
return objectMapper.readValue(json, clazz);
}
}
控制台输出:
SubClass(super=SuperClass(id=1, name=name))
- 3)
BeanUtils.copyProperties
使用的是 Spring 的
spring-beans
版本。
public class TestMain {
public static void main(String[] args) {
SuperClass superClass = new SuperClass(1, "name");
SubClass subClass = new SubClass();
BeanUtils.copyProperties(superClass, subClass);
System.out.println(subClass);
}
}
控制台输出:
SubClass(super=SuperClass(id=1, name=name))
API 差异
- Spring
spring-beans
版本:源对象source
在前面,目标对象target
在后面。
package org.springframework.beans;
public abstract class BeanUtils {
public static void copyProperties(Object source, Object target) throws BeansException {
}
- Apache
commons-beanutils
版本:源对象orig
在后面,目标对象dest
在前面。
package org.apache.commons.beanutils;
public class BeanUtils {
public static void copyProperties(final Object dest, final Object orig)
}
网友评论