Entity与Entity之间的相互转化
一。两个实体类的属性名称对应之间的转化
1.两个实体类
public class Entity1 { private Integer id;
private String name;
private Integer age;
private byte sex;
// get/set
} public class Entity2 {
private String name;
private Double sal;
private Integer age;
// get/set
}
2。Entity2Entity 转化类
public class Entity2Entity {
public static void main(String[] args) throws Exception {
Entity1 en = new Entity1(1, "zcj", 18, (byte)1);
Object parse = parse(en,new Entity2());
System.out.println(parse);
} public static <T, F> F parse(T src, F target) throws Exception{
Method[] srcMethods = src.getClass().getMethods();
Method[] targetMethod = target.getClass().getMethods();
for(Method m : srcMethods) {
if(m.getName().startsWith("get")) {
Object result = m.invoke(src);
for(Method mm : targetMethod) {
if(mm.getName().startsWith("set") && mm.getName().substring(3).
equals(m.getName().substring(3))) {
mm.invoke(target,result);
}
}
}
}
return target;
} }
3。运行结果
PersonDto [personId=1, personName=zcj, personAge=12, sal=12.0]
二。基于实体类中要转化的get方法或者属性进行转化
package com.entity.demo3; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import com.entity.demo.Entity1;
import com.entity.demo.Entity2; public class EntityUtil { public static void main(String[] args) {
Entity1 src = new Entity1(1, "zcj", 18, (byte)1);
Entity2 target = new Entity2();
// target = entity2entityByMethod(src,target);
target = entity2entityByField(src,target);
System.out.println(target);
} // 首字母转大写
public static String firstChartToUpper(String str) {
if (Character.isUpperCase(str.charAt(0))) {
return str;
}
StringBuffer sb = new StringBuffer();
return sb.append(Character.toUpperCase(str.charAt(0))).append(str.substring(1)).toString();
} /**
* 基于实体类中要转化的get方法获取
* @param src
* @param target
* @return
*/
public static <T, F> F entity2entityByMethod(T src, F target) {
Field[] targetFields = target.getClass().getDeclaredFields();
for (Field field : targetFields) {
try {
Method method = src.getClass().getMethod("get" + firstChartToUpper(field.getName()));
Object value = method.invoke(src);
field.setAccessible(true);
field.set(target, value);
} catch (Exception e) {
continue;
}
}
return target;
} /**
* 基于实体类中属性进行转换
* @param src
* @param target
* @return
*/
public static <T, F> F entity2entityByField(T src, F target) {
Field[] srcFields = src.getClass().getDeclaredFields();
Class<? extends Object> class1 = target.getClass();
for (Field field : srcFields) {
try {
field.setAccessible(true);
Object value = field.get(src);
if(value == null) {
continue;
}
Method mm = class1.getMethod("set"+firstChartToUpper(field.getName()),value.getClass());
mm.invoke(target, value);
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
return target;
} }
三。利用反射+注解进行转化
1.两个实体类
public class Pseron {
private String perId;
private String perName;
private String perAge;
private Double sal;
private Integer pno;
} public class PersonDto {
@RelMapper(value="perId")
private String personId;
@RelMapper(value="perName")
private String personName;
@RelMapper(value="perAge")
private String personAge;
private Double sal;
}
2.一个自定义的注解
//Target 注解的使用域,FIELD表示使用在属性上面,TYPE表示使用在类上面
@Target({ElementType.FIELD,ElementType.TYPE})
//Retention 设置注解的生命周期 ,这里定义为RetentionPolicy.RUNTIME 非常关键
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Mapper {
//自定义属性
String value() default "";
}
3.转化类
public class Entity2Dto {
public static void main(String[] args){
Object en2Dto = en2Dto(new Pseron("1","zcj", "12",12.0,null), new PersonDto());
System.out.println(en2Dto);
} public static Object en2Dto(Object src,Object target) {
Field[] targetFields = target.getClass().getDeclaredFields();
Class<? extends Object> srcFields = src.getClass();
String name;
for (Field field : targetFields) {
try {
field.setAccessible(true);
// 判断这个字段上是否有相应的注解信息(RelMapper.class)
if(field.isAnnotationPresent(Mapper.class)){
Mapper annotation = field.getAnnotation(Mapper.class);
name = annotation.value();
}else {
name = field.getName();
}
Field field2 = srcFields.getDeclaredField(name);
if(field2 != null) {
field2.setAccessible(true);
}
Object object = field2.get(src);
field.set(target, object);
}catch (Exception e) {
e.printStackTrace();
}
}
return target;
} }
Entity与Entity之间的相互转化的更多相关文章
- 分享公司Entity与DTO之间数据拷贝的方法
主题 最早以前自学java web的时候,数据库查询出来一个Entity对象(CMP对象).就直接传给前台展示了.并没有用到DTO对象,开始并没有觉得有什么不好...后来发现还是需要一些DTO对象来专 ...
- ASP.NET-MVC中Entity和Model之间的关系
Entity 与 Model之间的关系图 ViewModel类是MVC中与浏览器交互的,Entity是后台与数据库交互的,这两者可以在MVC中的model类中转换 MVC基础框架 来自为知笔记(Wiz ...
- Types of Entity in Entity Framework:
http://www.entityframeworktutorial.net/Types-of-Entities.aspx We created EDM for existing database i ...
- .NET Core Entity使用Entity Framework Core链接数据库
首先安装Nuget包 Install-package Microsoft.EntityFrameworkCore Install-package Microsoft.EntityFrameworkCo ...
- java string和int之间的相互转化
java 中string和int之间的相互转化 1 如何将字串 String 转换成整数 int? A. 有两个方法: 1). int i = Integer.parseInt([String]); ...
- 值类型之间的相互转化,运算符,if条件判断,循环,函数
值类型之间的相互转化 number | string | boolean 一.转换为boolean=>Boolean(a); var num = 10; var s = '123'; var b ...
- EntityFramework 学习 一 Colored Entity in Entity Framework 5.0
You can change the color of an entity in the designer so that it would be easy to see related groups ...
- Entity Framework Tutorial Basics(8):Types of Entity in Entity Framework
Types of Entity in Entity Framework: We created EDM for existing database in the previous section. A ...
- js 类型之间的相互转化
设置元素对象属性 var img = document.querySelector("img") img.setAttribute("src","ht ...
- Python中的列表,元组,字符串之间的相互转化
Python中的列表元组和字符串之间的相互转化需要利用,tuple(),list(),str(). 示例如下: >>> the_string = "hello I'am x ...
随机推荐
- css进阶 03-网页设计和开发中,关于字体的常识
03-网页设计和开发中,关于字体的常识 #前言 我周围的码农当中,有很多是技术大神,却常常被字体这种简单的东西所困扰. 这篇文章,我们来讲一讲关于字体的常识.这些常识所涉及到的问题,有很强的可操作性, ...
- docker 安装es跟kibana
首先docker 查询es docker search elasticsearch 在docker pull elasticsearch:7.9.3 docker在查询 kibana docker ...
- matplotlib的学习2-基本用法
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-1, 1, 50)#范围-1 到 1,个数是50 y = 2*x ...
- CVE-2019-0708_RDP漏洞利用
可以说是2019年影响比较大的一个漏洞了, 简述下这个漏洞: Windows系列服务器于2019年5月15号,被爆出高危漏洞,该漏洞影响范围较广如: windows2003.windows2008.w ...
- Python 炫技操作:安装包的八种方法,你知道吗?
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理 1. 使用 easy_install easy_install 这应该是最古老的包安装方式了,目前基 ...
- 数组单调性判断以及all和diff函数的用法
clc;clear all;close all; n = 1 ;x = zeros(100,1);while n~= 0 n = input('请输入向量的长度n(0退出程序):'); for i = ...
- Git设置记住账号密码
Git设置记住账号密码 添加如下配置 [credential] helper = store
- [leetcode]55.JumpGame动态规划题目:跳数游戏
/** * Given an array of non-negative integers, you are initially positioned at the first index of th ...
- nohup命令说明-转载
转自:https://www.ibm.com/developerworks/cn/linux/l-cn-nohup/ 我们知道,当用户注销(logout)或者网络断开时,终端会收到 HUP(hangu ...
- linux下网络设置和远程连接
配置ip.子网掩码.静态设置.开机启动ONBOOT网卡 /etc/sysconfig/network-scripts/ifcfg-eth0 重启网络 service network restart ...