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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM