题目描述:通过反射赋值源对象中的属性值到目标对象的具有相同类型和名称的属性
import java.lang.reflect.Field;
public class BeanUtils {
public static void copy(Object source,Object target){
//1.参数校验
if(source == null){
throw new IllegalArgumentException("Source object must be not null");
}
if(target == null){
throw new IllegalArgumentException("Target object must be not null");
}
//2.获取Class对象
Class sourceCls = source.getClass();
Class targetCls = target.getClass();
//3.获取Class对象中的Field(属性)
Field[] sourceFields = sourceCls.getDeclaredFields();
Field[] targetFields = targetCls.getDeclaredFields();
//4.通过sourceFields在targetFields找它元素相同(名字和类型)
for(Field sf : sourceFields){
for(Field tf : targetFields){
if(sf.getName().equals(tf.getName()) && sf.getType() == tf.getType()){
sf.setAccessible(true);
tf.setAccessible(true);
Object obj = null;
try {
obj = sf.get(source);
tf.set(target,obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
import java.util.Date;
public class TestBeanUtils {
public static void main(String[] args) {
Person person = new Person();
Student student = new Student();
person.setName("蔡徐坤");
person.setAge(28);
person.setSkill("唱跳rap篮球");
System.out.println("copy前");
System.out.println(person);
System.out.println(student);
System.out.println("copy后");
BeanUtils.copy(person,student);
System.out.println(person);
System.out.println(student);
}
}
class Person{
private String name;
private int age;
private String skill;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", skill='" + skill + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
}
class Student{
private String name;
private int age;
private Date birthday;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}