Merging the two objects using Reflection API
For example the class Animal has objects Tiger, Lion, following is show how to merge these objects using Reflection API
Main class
Output:
[Lion, 25, 120]
Tiger objects properties were overriden by Lion object properties.
For example the class Animal has objects Tiger, Lion, following is show how to merge these objects using Reflection API
1 2 3 4 5 6 7 8 9 | class Animal { private name; private age; private weight; ..setter/getters } |
Main class
1 2 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 | Class Main { public static void main(String[] args) { Animal tiger = new Animal(); tiger.setName("Tiger"); tiger.setAge("20"); tiger.setWeight("80"); Animal lion = new Animal(); lion.setName("Lion"); lion.setAge("25"); lion.setWeight("120"); merge(tiger,lion); sysout.println(tiger); } public static void merge(Object obj, Object update) { if (!obj.getClass().isAssignableFrom(update.getClass())) { return; } Method[] methods = obj.getClass().getMethods(); for (Method fromMethod : methods) { if (fromMethod.getDeclaringClass().equals(obj.getClass()) && fromMethod.getName().startsWith("get")) { String fromName = fromMethod.getName(); String toName = fromName.replace("get", "set"); try { Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType()); Object value = fromMethod.invoke(update, (Object[]) null); if (value != null) { toMetod.invoke(obj, value); } } catch (Exception e) { e.printStackTrace(); } } } } } |
Output:
[Lion, 25, 120]
Tiger objects properties were overriden by Lion object properties.
No comments:
Post a Comment