package com.iotek.classtype; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class FansheDemo { public static void main(String[] args) { // 2,生成一个学生对象(被复制的那个对象,原对象) Student student = new Student(1, "谭磊", 20); try { Student student2=(Student)ObjectCopuUtil.copyObject(student); System.out.println("复制成功"); System.out.println(student2.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 创建一个拷贝对象的工具类,内部提供一个拷贝方法 接收原对象 class ObjectCopuUtil { public static Object copyObject(Object object) throws Exception { // 3.获取Student对所对应类型的class对象(也就是Student这个类所对应的class对象) Class<?> class1 = object.getClass(); // 4.通过class对象的newInstance()方法来构建一个目标对象 Object objres = class1.newInstance(); // 5.获取class对象的get和set方法 for (Field fieldt : class1.getDeclaredFields()) { /*//得到属性所对应的get和set方法 String setMethodName="set" +fieldt.getName().substring(0, 1).toUpperCase() +fieldt.getName().substring(1); String getMethodName="get" +fieldt.getName().substring(0, 1).toUpperCase() +fieldt.getName().substring(1); //调用原对象的get方法获得属性值 Method getmethod=class1.getDeclaredMethod(getMethodName, new Class[] {}); Object value=getmethod.invoke(object, new Object[] {}); //调用目标对象的set方法来给属性赋值= Method setmethod=class1.getDeclaredMethod(setMethodName, new Class[] {fieldt.getType()}); setmethod.invoke(object, new Object[] {value});*/ //直接获取原对象属性的值 fieldt.setAccessible(true); Object value=fieldt.get(object); fieldt.set(objres, value); } return objres; } } // 1,声明一个学生类 class Student { private int id; private String name; private int age; public Student() { super(); } public Student(int id, String name, int age) { this.id = id; this.name = name; this.age = 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; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
原文地址:https://www.cnblogs.com/tanlei-sxs/p/9998774.html
时间: 2024-10-23 23:04:33