实体类需要先继承要复制的实体类
public class entityCope {
public static void main(String[] args) throws Exception {
a a = new a();
b b = new b();
b.setAddre("河北邯郸");
b.setHeight("179");
b.setIdno("130423");
b.setStrong("75kg");
a.ModeCope(b);
System.out.println("======"+a.getAddre());
}
}
class a extends b{
String name;
String sex;
String phone;
public void ModeCope(Object obj) throws Exception {
Class cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for(Field field:fields){
//获取属性类型及名称
String type = field.getType().getName();
String name = field.getName();
System.out.println(type+" "+name);
//下面方法任选其一
//通过name拼接字符串获取方法,得到get方法
//方法一
Method method = cls.getDeclaredMethod("get"+onUp(name));
Object objs1 = method.invoke(obj);
System.out.println(method.getName());
System.out.println(objs1.toString());
field.setAccessible(true);
field.set(this,objs1);
//获取属性值
//方法二
Object obj2 = field.get(obj);
System.out.println(obj2.toString());
field.setAccessible(true);
field.set(this,obj2);
}
}
public String onUp(String str){
char[] chars = str.toCharArray();
if(chars[0]>='a' && chars[0]<='z'){
chars[0] = (char) (chars[0]-32);
}
return new String(chars);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
class b{
String idno;
String addre;
String height;
String strong;
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
public String getAddre() {
return addre;
}
public void setAddre(String addre) {
this.addre = addre;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getStrong() {
return strong;
}
public void setStrong(String strong) {
this.strong = strong;
}
}