通過Java的反射機制來Copy一個對象

主函數:

package gdut.clb.reflect;

public class CopyReflect {

	/**
	 * @param args
	 */
	
	public static void main(String[] args)throws Exception {
		Student student = new Student() ;
		student.setId(new Long(1000)) ;
		student.setName("xinzi") ;
		student.setAge(22) ;
		
		Student copyStudent = (Student)CopyObject.copy(student) ;
		
		System.out.println("id: "+copyStudent.getId()+" ,name: "+copyStudent.getName()+" age: "+copyStudent.getAge()) ;
	}

}
//定義一個Student的類
class Student {
	
	private Long id ;
	private String name ;
	private int age ;
	public Student(){}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	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;
	}


以下這個類對對象進行復制:

package gdut.clb.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CopyObject {

	public static Object copy(Object object)throws Exception{
		Class<?> classType = object.getClass() ;
		Object copyObject = classType.getConstructor(new Class[]{}).newInstance(new Object[]{}) ;
		
		Field[] fields = classType.getDeclaredFields() ;
		String name = null ;
		String setterName = null ;
		String getterName = null ;
		for(Field field : fields){
			name = field.getName() ;
			setterName = "set"+name.substring(0,1).toUpperCase()+name.substring(1) ;
			getterName = "get"+name.substring(0,1).toUpperCase()+name.substring(1) ;
			Method getterMethod = classType.getDeclaredMethod(getterName, new Class[]{}) ;
			Method setterMethod = classType.getDeclaredMethod(setterName, field.getType()) ;
			setterMethod.invoke(copyObject, new Object[]{getterMethod.invoke(object, new Object[]{})}) ;
		}
		
		return copyObject ;
	}
}

}

運行結果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章