反射一属性赋值一用反射机制给相同属性名赋值

利用反射机制给相同属性名赋值

1 请粘贴 运行

package demo.springboot.reflection;

import org.testng.annotations.Test;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * 

* 利用反射进行相同属性的赋值 *

* * @author shan yue feng cheng * @date 2019/5/23 0023 */ public class ClassUtil { //需要最后赋的值 public static final User user = new User(); static{ user.setCreateTime(new Date()); user.setCreator("luocheng"); } //创建指定类型的返回Object public T createReflectionEntity(Object object,Class clazz) throws Exception{ Field[] fields = clazz.getDeclaredFields(); for (Field field : fields){ object = setFieldValueByFieldName(field.getName(),object); } return (T) object; /** * 创建对象的几种方式 * 1new * 2clone * 3反序列化 * 4反射 * Object o = clazz.newInstance(); */ } public Object setFieldValueByFieldName(String fieldName, Object object) throws Exception{ Class aClass = object.getClass(); Field declaredField = aClass.getDeclaredField(fieldName); //放开类型检查 declaredField.setAccessible(true); if ("creator".equals(fieldName)){ declaredField.set(object,user.getCreator()); } if("createTime".equals(fieldName)){ declaredField.set(object,user.getCreateTime()); } return object; } @Test public void test() throws Exception{ LocalUser localUser = new LocalUser(); localUser.setUserName("localLuoCheng"); ClassUtil classUtil = new ClassUtil(); LocalUser reflectionEntity = classUtil.createReflectionEntity(localUser, LocalUser.class); System.out.println(reflectionEntity); } } //想要给LocalUser赋值 class LocalUser{ private String userName; private String creator; private Date createTime; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "LocalUser{" + "userName='" + userName + '\'' + ", creator='" + creator + '\'' + ", createTime=" + createTime + '}'; } } class User{ private String creator; private Date createTime; public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }

你可能感兴趣的:(Java成神之路)