閱讀851 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Java中利用反射原理拷貝對象

測試類
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

public class Test
{
/**
* 拷貝對象方法
*/
public static Object copy(Object objSource) 
              throws IllegalArgumentException, SecurityException, InstantiationException, 
                     IllegalAccessException, InvocationTargetException,NoSuchMethodException
{
// 獲取源對象類型
Class<?> clazz = objSource.getClass();
// 獲取源對象構造函數
Constructor<?> construtctor = clazz.getConstructor();
// 實例化出目標對象
Object objDes = construtctor.newInstance();
// 獲得源對象所有屬性
Field[] fields = clazz.getDeclaredFields();
// 遍曆所有屬性
for (int i = 0; i < fields.length; i++)
{
// 屬性對象
Field field = fields[i];
// 屬性名
String fieldName = field.getName();
// 獲取屬性首字母
String firstLetter = fieldName.substring(0, 1).toUpperCase();
// 拚接get方法名如getName
String getMethodName = "get" + firstLetter + fieldName.substring(1);
// 得到get方法對象
Method getMethod = clazz.getMethod(getMethodName);
// 對源對象調用get方法獲取屬性值
Object value = getMethod.invoke(objSource);

// 拚接set方法名
String setMethodName = "set" + firstLetter + fieldName.substring(1);
// 獲取set方法對象
Method setMethod = clazz.getMethod(setMethodName, new Class[] { field.getType() });
// 對目標對象調用set方法裝入屬性值
setMethod.invoke(objDes, new Object[] { value });
}
return objDes;
}


public static void main(String[] args) 
        throws IllegalArgumentException, SecurityException,InstantiationException,                        
                       IllegalAccessException,InvocationTargetException, NoSuchMethodException
{
// 學生源對象
Student studentSource = new Student();
studentSource.setNum(1);
studentSource.setName("xy");
studentSource.setBirthDay(new Date());

 // 複製學生對象
Student studentDes = (Student) copy(studentSource);
System.out.println(studentDes.getName());
}
}

實體類
public class Student
{
private int num;
private String name;
private Date birthDay;

public Student()
{
super();
}

public Student(int num, String name, Date birthDay)
{
super();
this.num = num;
this.name = name;
this.birthDay = birthDay;
}

public int getNum()
{
return num;
}

public void setNum(int num)
{
this.num = num;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public Date getBirthDay()
{
return birthDay;
}

public void setBirthDay(Date birthDay)
{
this.birthDay = birthDay;
}

}

注意因為在copy方法中調用的newInstance是不帶參數的,所以student類中必須有空構造方法。


最後更新:2017-04-04 07:36:13

  上一篇:go centos 網易yum源出錯解決辦法 mark
  下一篇:go C# DataSet.Clear 方法