Java反射 拷贝构造 深拷贝
温馨提示:
本文最后更新于 2021年12月12日,已超过 1,234 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
Java反射 拷贝构造 深拷贝
一:常用方法
(1)object.getClass()方法是获得调用该方法的对象的类;
(2)getClass().getName()可以得到该类的路径;
(3)classType.getConstructor()获取指定参数的构造函数;
(4)classType.getConstructor().newInstance(new Object[]{});使用获取到的指定构造函数构造一个对像;
(5)classType.getConstructors();获取所有的public构造函数,返回一个数组;
(6)classType.getDeclaredConstructors();获取所有的构造函数,返回一个数组;
(7)classType.getDeclaredMethods();获取所有的方法,返回一个数组;
(8)classType.getMethods();获取所有的public方法;
(9)classType.getMethod();获取指定方法名的方法;
(10)classType.getFields();获取所有的public属性;
(11)classType.getField();指定属性名获取属性;
(12)classType.getDeclaredFields();获取所有的属性;
(13)Method.invoke();调用执行指定对你的指定方法;
(14)Class.forName();通过className(类名)生成Class;
二:使用反射实现一个copy构造
public class Customer {
private Long id;
private String name;
private int age;
public Customer() {}
public Customer(String name) {
this.name = name;
}
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public Customer(Long id, String name, int age) {
this.id = id;
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;
}
}
public class ReflectCopy {
public Object copy(Object object) throws Exception{
//获得对象的类型
Class classType = object.getClass();
System.out.println("Class: " + classType.getName());
Class claseName = Customer.class;
System.out.println("Class<Customer>: " + claseName.getName());
//通过默认构造方法创建一个新的对象
Class[] classes = new Class[]{};
Object objectCopy = classType.getConstructor(classes).newInstance(new Object[]{});
// Constructor con = classType.getConstructor(classes);
Field fields[] = classType.getDeclaredFields();
for(int i = 0; i < fields.length; i++){
Field field = fields[i];
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
//获得和属性对应的getXXX()方法的名字
String getMethodName = "get" + firstLetter + fieldName.substring(1);
//获得和属性对应的setXXX()方法的名字
String setMethodName = "set" + firstLetter + fieldName.substring(1);
//获得和属性对应的getXXX()方法
Method getMethod = classType.getMethod(getMethodName, new Class[]{});
//获得和属性对应的setXXX()方法
Method setMethod = classType.getMethod(setMethodName, new Class[]{field.getType()});
//调用原对象的getXXX()方法
Object value = getMethod.invoke(object, new Object[]{});
System.out.println(fieldName + ":" + value);
//调用拷贝对象的setXXX()方法
setMethod.invoke(objectCopy, new Object[]{value});
System.out.println("objectCopy: " + fieldName + ":" + value);
}
return objectCopy;
}
public static void main(String[] args) throws Exception {
ReflectCopy tester = new ReflectCopy();
tester.copy(new Customer(1L, "lusoel", 30));
}
}
正文到此结束
- 本文标签: Java
- 本文链接: https://www.linxyun.com/blog/article/1
- 版权声明: 本文由林栖云 原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权