父类属性值的copy
2024-09-04 15:26:51
最近开发中遇到这样一个问题将父类的属性值copy到子类中,从而对子类添加一些其他属性。
父类:
package com.jalja.org.jms.test01; import java.util.Date; public class User {
private Integer id;
private String name;
private Date time;
public User() {
super();
}
public User(String name, Date time) {
super();
this.name = name;
this.time = time;
}
public User(Integer id, String name, Date time) {
super();
this.id = id;
this.name = name;
this.time = time;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
子类:
package com.jalja.org.jms.test01; public class UserVO extends User{
private int sex;
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
package com.jalja.org.jms.test01; import java.lang.reflect.Field;
import java.util.Date; public class CopyObj {
/**
* 我们的业务是需要在现有的类上扩展一些属性供视图层使用
* 1、在原有类上扩展一些属性也可以实现,但这样需要在别人的代码中直接更改,个人认为不是很好。
* 2、写一个扩展类 UserVO 继承原类 User
* @param args
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
User user=new User("2131",new Date());
//将父类强转为子类出现异常Exception in thread "main" java.lang.ClassCastException:
//UserVO vo1=(UserVO) user;
//vo1.setSex(0); UserVO vo2=(UserVO) copyObj(user,new UserVO());
vo2.setSex(0);
System.out.println(vo2.getName()); }
/** 子对象copy父对象的属性值
* copyObj 继承 targetObj
* @param targetObj 被copy的目标对象
* @param copyObj copy后的对象
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static <T> T copyObj(T targetObj,T copyObj ) throws IllegalArgumentException, IllegalAccessException{
Field [] fields=targetObj.getClass().getDeclaredFields();
Field [] fieldsvo=copyObj.getClass().getSuperclass().getDeclaredFields();
for(Field f:fields){
f.setAccessible(true);
for(Field f2:fieldsvo){
f2.setAccessible(true);
if(f.get(targetObj)!=null&& f.getName().toString().equals(f2.getName().toString())){
f2.set(copyObj,f.get(targetObj)) ;
}
}
}
return copyObj;
}
}
最新文章
- Oracle sql连接
- maven 问题解决 tools以及jconsole两个jar包 无效
- 《BI那点儿事》Microsoft 时序算法——验证神奇的斐波那契数列
- 智能车学习(十七)&mdash;&mdash;舵机学习
- 模拟 POJ 2996 Help Me with the Game
- Xcode5.1离线下载安装及使用iOS5模拟器进行开发调试的方法
- Linux之TCPIP内核参数优化
- Eclipse打开当前所属文件所在windows中的文件夹
- asp.net2.0安全性(1)--用户角色篇(代码实现1)--转载来自车老师
- EmpyoyeeManger_1.0
- 干了这杯Java之Vector
- Swift 3中新的访问控制关键字fileprivate和open
- platform驱动分离
- 基于ionic4、cordova搭建android开发环境
- Luogu P2657 [SCOI2009]windy数
- 调用 微信接口报错 {";errcode";:48001,";errmsg";:";api unauthorized, hints: [ req_id: 1QoCla0699ns81 ]";}
- 初识Linux------文件管理
- 【C++】operator new/new operator/placement new之间的区别
- 201621123018《Java程序设计》第6周学习报告
- ASP.NET HttpModule URL 重写 (一) 【Z】