初始反射
来源:互联网 发布:柏拉图交友软件 编辑:程序博客网 时间:2024/06/05 02:13
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
-
-
-
-
-
-
-
- public class Reflect {
-
- public static void main(String[] args) throws Exception {
- Person person = new Person("walkingdog", 20);
- person.setId(2009324116L);
- Person personCopy = (Person)new Reflect().copy(person);
- System.out.println(personCopy.getId() + " " + personCopy.getName() + " " + personCopy.getAge());
- }
-
- public Object copy(Object object) throws Exception{
-
-
-
-
- Class<?> classType = object.getClass();
-
-
-
- Constructor<?> constructor = classType.getConstructor(new Class<?>[]{});
-
- Object objectCopy = constructor.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, value);
- }
- return objectCopy;
- }
- }
-
-
- class Person{
- private Long id;
- private String name;
- private int age;
-
-
- public Person() {}
-
- public Person(String name, int age){
- this.name = name;
- this.age = age;
- }
-
-
- }
1 0