读书少,文笔差,写的不好望勿喷
前两天,我开发的部分需要通过历史数据来重新引用业务单,由于这是数据是从旧系统里来的,对象名于新系统的不一样,为了方便区分于管理,也不能一样.
但是新旧对象简单参数大多是样的,我第一反应就是通过反射来对对象进行拷贝.
由于学艺不精,于是去百度了反射的写法.
写完了,测试两个不同名称的对象拷贝也成功了,于是去继续任务....然而,并不行......getFieds是那不到父类的参数名的.
我不知道是不是jdk7的缘故,看了好多别人的方法我都没能拿到,最后问了同事,原来我司早有工具,于是不写自己的方法了.
下班后深感惭愧.即使我没有公司框架写的好,还是应该写一下的,同时也为方便初学者参考一下,不要浪费太多的时间.
好,下面上代码
工具类的代码
package lsoft.reflect.tool;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@SuppressWarnings("all")
public class ReflectUtils {
/** 对象属性拷贝 */
public static void copyPropertys(Object resource, Object target) {
copyPropertys(resource, target, null);
}
/** 对象属性拷贝
* @param ignoreSet 忽略(不拷贝的参数)
* */
public static void copyPropertys(Object resource, Object target, Set<String>ignoreSet) {
if(null == ignoreSet) {
ignoreSet = new HashSet<>();
}
Class resurceClazz = resource.getClass();
Class targetClazz = target.getClass();
Set<String> fieldNameSet = getFieldNameSet(resurceClazz);
Set<String> targetFielNameSet = getFieldNameSet(targetClazz);
Iterator<String> fieldNameIter = fieldNameSet.iterator();
while(fieldNameIter.hasNext()) {
String fieldName = fieldNameIter.next();
if(!ignoreSet.contains(fieldName) && !"id".equals(fieldName)) {//id不拷贝
Iterator<String> targetFieldsIter = targetFielNameSet.iterator();
while(targetFieldsIter.hasNext()) {
String targetFielName = targetFieldsIter.next();
if(targetFielName.equals(fieldName)) {
try {
getSetMethod(targetClazz, targetFielName).invoke(target,getGetMethod(resurceClazz, fieldName).invoke(resource));
} catch (IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
/** 获取实体及其非Object的所有父类定义的字段对应的Field */
public static List<Field> getFields(Class clazz) {
List<Field> fieldList = new ArrayList<>();
if(!clazz.getName().equals(Object.class.getName())) {
fieldList.addAll(getFields(clazz.getSuperclass()));
}
Field [] fieldArray = clazz.getDeclaredFields();
for(Field field : fieldArray) {
fieldList.add(field);
}
return fieldList;
}
/** 获取所有参数对应的Setter/getter 方法 */
public static List<Method> getMethods(Class clazz) {
List<Method> methodList = new ArrayList<>();
for(Method method : clazz.getMethods()) {
if(getFieldNameSet(clazz).contains(toPropertyName(method.getName()))) {
methodList.add(method);
}
}
return methodList;
}
/** 获取所有的Getter方法 */
public static List<Method> getGetMethods(Class clazz) {
List<Method> methodList = new ArrayList<>();
for(Method method : clazz.getMethods()) {
if(getFieldNameSet(clazz).contains(toPropertyName(method.getName())) && method.getName().startsWith("get")) {
methodList.add(method);
}
}
return methodList;
}
/** 获取所有的Setter方法 */
public static List<Method> getSetMethods(Class clazz) {
List<Method> methodList = new ArrayList<>();
for(Method method : clazz.getMethods()) {
if(getFieldNameSet(clazz).contains(toPropertyName(method.getName())) && method.getName().startsWith("set")) {
methodList.add(method);
}
}
return methodList;
}
/** 对象参数名的集合 */
public static Set<String> getFieldNameSet(Class clazz) {
Set<String> fieldNameSet = new HashSet<>();
for(Field field : getFields(clazz)) {
fieldNameSet.add(field.getName());
}
return fieldNameSet;
}
/** 通过参数名获得Getter方法 */
public static Method getGetMethod(Class clazz,String propertyName) {
Method method = null;
try {
method = clazz.getMethod(toGetterName(propertyName));
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
return method;
}
/** 通过参数名获得Setter方法 */
public static Method getSetMethod(Class clazz,String propertyName) {
Method method = null;
try {
Field field = null;
List<Field> fieldList = getFields(clazz);
for(Field f : fieldList) {
if(f.getName().equals(propertyName)) {
field = f;
}
}
if(null == field) {
throw new NoSuchFieldException("no such filed [" + propertyName + "]");
}
method = clazz.getMethod(toSetterName(propertyName),field.getType());
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return method;
}
/** 通过参数名获得Getter方法名 */
public static String toGetterName(String propertyName) {
return "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
}
/** 通过参数名获得Setter方法名 */
public static String toSetterName(String propertyName) {
return "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
}
/** 通过Getter/Setter方法名获得参数名 */
public static String toPropertyName(String methodName) {
return methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
}
}
基实体
package lsoft.base.entity;
/**所有的实体都继承该类*/
public abstract class BaseEntity {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "BaseEntity [id=" + id + "]";
}
}
基类
package lsoft.com.entity.abstractEntity;
import lsoft.base.entity.BaseEntity;
/** 用户基类 */
public abstract class AbstractUser extends BaseEntity{
private String name;
private String password;
private String email;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return super.toString() + "AbstractUser [name=" + name + ", password=" + password
+ ", email=" + email + ", age=" + age + "]";
}
}
用户类package lsoft.com.entity;
import lsoft.com.entity.abstractEntity.AbstractUser;
/** 用戶类 *///我司的实体架构大概就是这个样子的
public class User extends AbstractUser{
}
用户历史类
package lsoft.com.entity;
import lsoft.com.entity.abstractEntity.AbstractUser;
/** 用户历史类 */
public class UserHistory extends AbstractUser{
}
测试类
package l.com;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import lsoft.com.entity.User;
import lsoft.com.entity.UserHistory;
import lsoft.reflect.tool.ReflectUtils;
public class TestReflectUtils {
public static void main(String[] args) {
//showMethods();
//showGetMethods();
//showSetMethods();
//showGetMethod(User.class, "name");
//showSetMethod(User.class, "name");
testCopy();
}
//测试不同对象间的对参数拷贝
public static void testCopy() {
User user = new User();
user.setId("111");
user.setAge(15);
user.setEmail("abcd@188.com");
user.setName("admin");
user.setPassword("123abc");
UserHistory historyUser = new UserHistory();
ReflectUtils.copyPropertys(user, historyUser, null);
System.out.println(historyUser);
}
//测试单个get方法
public static void showGetMethod(Class clazz, String name) {
System.out.println(ReflectUtils.getGetMethod(clazz, name).getName());
}
//测试单个set方法
public static void showSetMethod(Class clazz, String name) {
User user = new User();
Method method = ReflectUtils.getSetMethod(clazz, name);
try {
method.invoke(user, "admin");
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(user.getName());
}
//测试所有的property对应的set/get方法
public static void showMethods() {
for(Method method : ReflectUtils.getMethods(User.class)) {
System.out.println(method.getName());
}
}
//测试拿到的get方法
public static void showGetMethods() {
for(Method method : ReflectUtils.getGetMethods(User.class)) {
System.out.println(method.getName());
}
}
//测试拿到的set方法
public static void showSetMethods() {
for(Method method : ReflectUtils.getSetMethods(User.class)) {
System.out.println(method.getName());
}
}
}
这些都是很简单的东西,除了上代码,我也没什么好讲的了,
*注:代码写的不怎么样,仅供参考,不建议学习