package com.dzy.reflction;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Reflect {
public static void main(String[] args) {
TestBean tb=new TestBean();
tb.setName("宇智波佐助");
tb.setAge(12);
Reflect rf=new Reflect ();
try {
TestBean tbCopy=(TestBean)rf.copy(tb);
System.out.print(tbCopy.getName()+"-----"+tbCopy.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 作者:宇智波佐助
* 日期:2015-3-25
* 时间:下午
* @return 返回一个超类
* @throws IllegalAccessException
* @throws Exception
*/
public Object copy(Object obj) throws Exception
{
Class classtype=obj.getClass();
System.out.println(classtype.getName());
Object objectcopy=classtype.newInstance();
Field fis[]=classtype.getDeclaredFields();
for (int i = 0; i < fis.length; i++) {
Field field = fis[i];
System.out.println(field.getName());
String firstChar=field.getName().substring(0,1).toUpperCase();
System.out.println(firstChar);
String getMethoadName="get"+firstChar+field.getName().substring(1);
System.out.println(getMethoadName);
String setMethoadName="set"+firstChar+field.getName().substring(1);
System.out.println(setMethoadName);
Method getMethod=classtype.getMethod(getMethoadName, new Class[]{});
Method setMethod=classtype.getMethod(setMethoadName, new Class[]{field.getType()});
Object value=getMethod.invoke(obj, new Object[]{});
setMethod.invoke(objectcopy, new Object[]{value});
}
return objectcopy;
}
}
class TestBean
{
private int age;
private String name;
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}