经过了上一次对反射的初步认知,最近又接触到了后,做了一个小demo,感觉这次带了一点理解去做的,比第一次接触反射好了许多。
上次学习的链接,有一些反射用的基础语句。https://www.cnblogs.com/deepSleeping/p/9381785.html
package deep.blob.test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.Test; import deep.blob.entity.Employee; public class demo { @Test public void fun(){ Employee emp = new Employee(); emp.setId("1001"); emp.setName("张三"); emp.setGender("男"); emp.setAge(21); cloneEmp(emp); } private Object cloneEmp(Object emp) { //1.获得需要克隆的类的class对象 Class<?> clazz = emp.getClass(); //2.获得所有属性 Field[] fields = clazz.getDeclaredFields(); //3.定义被克隆的对象 Object newInstance = null; try { newInstance = clazz.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } //4.遍历所有的属性并获得值 for(Field field : fields){ try { if (!field.getName().equals("serialVersionUID")) { //设置可以访问private的属性 field.setAccessible(true); //获取克隆对象的对应属性的值并赋值给被克隆对象的对应属性名的属性 field.set(newInstance, field.get(emp)); } } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Method method = null; try { method = clazz.getMethod("toString"); System.out.println(method.invoke(newInstance)); } catch (NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newInstance; } }
1 package deep.blob.entity; 2 3 import java.io.Serializable; 4 5 /** 6 * 员工实体类 7 * @author DeepSleeping 8 * 9 */ 10 public class Employee implements Serializable{ 11 12 private static final long serialVersionUID = 1L; 13 14 private String id; 15 private String name; 16 private String gender; 17 private Integer age; 18 19 public String getId() { 20 return id; 21 } 22 public void setId(String id) { 23 this.id = id; 24 } 25 public String getName() { 26 return name; 27 } 28 public void setName(String name) { 29 this.name = name; 30 } 31 public String getGender() { 32 return gender; 33 } 34 public void setGender(String gender) { 35 this.gender = gender; 36 } 37 public Integer getAge() { 38 return age; 39 } 40 public void setAge(Integer age) { 41 this.age = age; 42 } 43 44 @Override 45 public String toString() { 46 return this.getId() + ":" + this.getName(); 47 } 48 49 }
原文地址:https://www.cnblogs.com/deepSleeping/p/9799914.html
时间: 2024-10-08 06:22:03