- package com.knowyou.reflect;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- /**
- *
- * 利用反射把一个对象的属性值copy给新的对象
- * @author byr216
- *
- */
- public class ReflectTest2 {
- public Object copyStudent(Student st) throws Exception {
- Class<?> stClass = st.getClass();// 获取对象的class对象
- Object stObject = stClass.newInstance(); // 创建获取到的class对象的实例
- // Constructor ct = stClass.getConstructor(String.class, int.class);
- // Object stObject = ct.newInstance("lisi",45);
- // System.out.println(ct.getDeclaringClass());
- Field[] fields = stClass.getDeclaredFields();// 获取获取到的class对象的私有属性集合
- for (Field field : fields) { // 遍历获取到的属性,并把传入的对象的属性值赋给新对象
- String m = field.getName(); // 获取属性的名字
- String setName = "set" + m.substring(0, 1).toUpperCase()
- + m.substring(1); // 获取类的set方法名
- String getName = "get" + m.substring(0, 1).toUpperCase()
- + m.substring(1);// 获取类的get方法名
- Method setMethod = stClass.getMethod(setName, field.getType()); // 获取类的set方法
- Method getMethod = stClass.getMethod(getName, new Class[0]); // 获取类的get方法
- Object getField = getMethod.invoke(st, new Object[0]); // 获取传入对象的属性值
- setMethod.invoke(stObject, getField);// 把获取传入对象的属性值赋给新对象
- }
- return stObject;
- }
- public static void main(String[] args) throws Exception {
- ReflectTest2 rc = new ReflectTest2();
- Student st = new Student("zhangsan", 23);
- Student ob = (Student) rc.copyStudent(st);
- System.out.println(ob.getName() + ":" + ob.getId());
- }
- }
- class Student {
- private String name;
- private int id;
- public Student() {
- }
- public Student(String name, int id) {
- this.name = name;
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- }
复制代码
|
|