反射学习

2014-11-24 02:03:56 · 作者: · 浏览: 0

package cn.lxl.reflect;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class ReflectTest1 {

public Object copy(Object obj) throws Exception {

Class< > classType = obj.getClass();

Constructor< > testConstructor = classType

.getConstructor(new Class[] {});

Object testInstance = testConstructor.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(obj, new Object[] {});

setMethod.invoke(testInstance, new Object[] { value });

}

return testInstance;

}

public static void main(String[] args) throws Exception {

Customer customer = new Customer("tom", 26);

customer.setId(1L);

ReflectTest1 test = new ReflectTest1();

Customer customer2 = (Customer) test.copy(customer);

System.out.println(customer2.getId() + "," + customer2.getName() + ","

+ customer2.getAge());

}

}

class Customer {

private Long id;

private String name;

private int age;

public Customer() {

}

public Customer(String name, int age) {

this.name = name;

this.age = age;

}

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;

}

}

本文出自 “Jxiaolei” 博客