package com.test.cn;
import java.lang.reflect.Field;
/**
* Java 反射之属性练习。
*
* @author Wanggc
*/
public class ReflectionTest {
public static void main(String[] args) throws Exception {
// 建立学生对象
Student student = new Student();
// 为学生对象赋值
student.setStuName("Wanggc");
student.setStuAge(24);
// 建立拷贝目标对象
Student destStudent = new Student();
// 拷贝学生对象
copyBean(student, destStudent);
// 输出拷贝结果
System.out.println(destStudent.getStuName() + ":"
+ destStudent.getStuAge());
}
/**
* 拷贝学生对象信息。
*
* @param from
* 拷贝源对象
* @param dest
* 拷贝目标对象
* @throws Exception
* 例外
*/
private static void copyBean(Object from, Object dest) throws Exception {
// 取得拷贝源对象的Class对象
Class<?> fromClass = from.getClass();
// 取得拷贝源对象的属性列表
Field[] fromFields = fromClass.getDeclaredFields();
// 取得拷贝目标对象的Class对象
Class<?> destClass = dest.getClass();
Field destField = null;
for (Field fromField : fromFields) {
// 取得拷贝源对象的属性名字
String name = fromField.getName();
// 取得拷贝目标对象的相同名称的属性
destField = destClass.getDeclaredField(name);
// 设置属性的可访问性
fromField.setAccessible(true);
destField.setAccessible(true);
// 将拷贝源对象的属性的值赋给拷贝目标对象相应的属性
destField.set(dest, fromField.get(from));
}
}
}
/**
* 学生类。
*/
class Student {
private String stuName;
private int stuAge;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
}
import java.lang.reflect.Field;
/**
* Java 反射之属性练习。
*
* @author Wanggc
*/
public class ReflectionTest {
public static void main(String[] args) throws Exception {
// 建立学生对象
Student student = new Student();
// 为学生对象赋值
student.setStuName("Wanggc");
student.setStuAge(24);
// 建立拷贝目标对象
Student destStudent = new Student();
// 拷贝学生对象
copyBean(student, destStudent);
// 输出拷贝结果
System.out.println(destStudent.getStuName() + ":"
+ destStudent.getStuAge());
}
/**
* 拷贝学生对象信息。
*
* @param from
* 拷贝源对象
* @param dest
* 拷贝目标对象
* @throws Exception
* 例外
*/
private static void copyBean(Object from, Object dest) throws Exception {
// 取得拷贝源对象的Class对象
Class<?> fromClass = from.getClass();
// 取得拷贝源对象的属性列表
Field[] fromFields = fromClass.getDeclaredFields();
// 取得拷贝目标对象的Class对象
Class<?> destClass = dest.getClass();
Field destField = null;
for (Field fromField : fromFields) {
// 取得拷贝源对象的属性名字
String name = fromField.getName();
// 取得拷贝目标对象的相同名称的属性
destField = destClass.getDeclaredField(name);
// 设置属性的可访问性
fromField.setAccessible(true);
destField.setAccessible(true);
// 将拷贝源对象的属性的值赋给拷贝目标对象相应的属性
destField.set(dest, fromField.get(from));
}
}
}
/**
* 学生类。
*/
class Student {
private String stuName;
private int stuAge;
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
}