Java 将父类的值传递给子类

 1 public class FatherToChild {
 2 
 3     public static <T> QuotesMergePlusPriceDto fatherToChild(T father, T child) throws Exception {
 4         if (child.getClass().getSuperclass() != father.getClass()) {
 5             throw new Exception("child 不是 father 的子类");
 6         }
 7         Class<?> fatherClass = father.getClass();
 8         Field[] declaredFields = fatherClass.getDeclaredFields();
 9         for (int i = 0; i < declaredFields.length; i++) {
10             Field field = declaredFields[i];
11             Method method = fatherClass.getDeclaredMethod("get" + upperHeadChar(field.getName()));
12             Object obj = method.invoke(father);
13             field.setAccessible(true);
14             field.set(child, obj);
15         }
16         return null;
17     }
18 
19     public static String upperHeadChar(String in) {
20         String head = in.substring(0, 1);
21         String out = head.toUpperCase() + in.substring(1, in.length());
22         return out;
23     }
24 }

参考:https://blog.csdn.net/qq_36354669/article/details/79807994

posted @ 2021-01-25 16:29  宁任翃  阅读(1641)  评论(0编辑  收藏  举报