这个方法太实用了。
分享给你们
方法用来做什么?
text
1
如果当2个对象中有相同的属性,则可以使用改工具方法。省掉set方法 ,如果属性未null也不会报错
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 属性的拷贝转移
* @param news 被改变的属性
* @param worn 被转移数据的对象
* @param <Y> 泛型
* @author 邵嘉喜
*/
public <Y> void CopyProper(Y news,Y worn) throws IllegalAccessException, InstantiationException {
Class<?> newsClass = news.getClass();
Class<?> wornClass = worn.getClass();
// //实例化对象
// Object newsObj = newsClass.newInstance();
// Object wornObj = wornClass.newInstance();
//获取类中所有的属性(被转移数据的对象)
Field[] newsFields = newsClass.getDeclaredFields();
//获取类中所有的属性(被改变的属性)
Field[] wornFields = wornClass.getDeclaredFields();
for(Field newsfield:newsFields){
newsfield.setAccessible(true);
//获取属性名称
String name = newsfield.getName();
//获取属性值
Object pro = newsfield.get(news);
for (Field wornField : wornFields) {
wornField.setAccessible(true);
//获取属性名
Object wornName = wornField.getName();
boolean isFinal = Modifier.isFinal(wornField.getModifiers());
Object o = wornField.get(worn);
if(name.equals(wornName) && !isFinal && o == null && pro != null){
wornField.set(worn,pro);
break;
}
}
}
}
使用方法
java
1
2
3
4
5
6
7
8
TessayInfo info = new TessayInfo();//需要被赋值的对象
try {
ProperUtils.CopyProper(tEssay,info);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}

评论
登录后即可评论
分享你的想法,与作者互动
暂无评论