java反射

 

package voyage.reflector;

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

public class Reflect {

/**
* @param args
*/
public Object copy(Object object) throws Exception
{
Class<?> classType=object.getClass();
Object objectCopy=classType.getConstructor(new Class[]{})
.newInstance(new Object[]{});
Field[] fields=classType.getDeclaredFields();
for(Field field:fields)
{
String name=field.getName();
String firstLetter=name.substring(0,1).toUpperCase();
String getMethodName="get"+firstLetter+name.substring(1);
String setMethodName="set"+firstLetter+name.substring(1);
Method getMethod=classType.getMethod(getMethodName, new Class[]{});
Method setMethod=classType.getMethod(setMethodName, new Class[]{field.getType()});
Object value=getMethod.invoke(object, new Object[]{});
setMethod.invoke(objectCopy, new Object[]{value});
}
return objectCopy;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
User user1=new User("bai",20);
user1.setId(1);
Reflect reflect=new Reflect();
User user2=(User) reflect.copy(user1);
System.out.println(user2.getId()+","+user2.getName()+","+user2.getAge());
}
}
class User
{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int 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;
}
public User()
{

}
public User(String name,int age)
{
this.name=name;
this.age=age;
}
}

你可能感兴趣的:(java 反射)