| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 
 | import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 
 public class Demo {
 public static void main(String[] args) throws Exception {
 A a=new A();
 B b=new B();
 List<String> strings = new ArrayList<>();
 strings.add("111");
 strings.add("2323");
 a.setNames(new HashSet<String>(strings));
 a.setA("a");
 a.setB("b");
 fatherToChild(a,b);
 b.getNames().forEach(System.out::println);
 System.out.println(b.getA());
 }
 
 public static <T>void fatherToChild(T father,T child) throws Exception {
 if (child.getClass().getSuperclass()!=father.getClass()){
 throw new Exception("child 不是 father 的子类");
 }
 Class<?> fatherClass = father.getClass();
 Field[] declaredFields = fatherClass.getDeclaredFields();
 for (int i = 0; i < declaredFields.length; i++) {
 
 Field field=declaredFields[i];
 System.out.println(field.toGenericString());
 
 if(field.toGenericString().contains("final")){
 continue;
 }
 Method method=fatherClass.getDeclaredMethod("get"+upperHeadChar(field.getName()));
 Object obj = method.invoke(father);
 field.setAccessible(true);
 field.set(child,obj);
 }
 
 }
 
 
 
 
 public static String upperHeadChar(String in) {
 String head = in.substring(0, 1);
 String out = head.toUpperCase() + in.substring(1, in.length());
 return out;
 }
 }
 
 |