I am trying to write a copy method which can be used to copy a bean to bean by mapping the property names. if the source object is a cloneable object m cloning it and trying to return it to the calling method. but in calling method it change made in the called method is not reflecting
you might understand if u look at the below code
public class Main {
public static void main(String[] args) {
HashMap<Object, Object> source = new HashMap<Object, Object>();
source.put("test1", "test1");
source.put("test2", "test2");
source.put("test3", "test3");
HashMap<Object, Object> destination = new HashMap<Object, Object>();
Main m = new Main();
Main.beanCopy(source, destination);
System.out.println("caller - " + destination);
}
public static void beanCopy(Object source, Object destination) {
if (source.getClass() == destination.getClass()
&& Cloneable.class.isInstance(source)) {
Class<? extends Object> cl = source.getClass();
try {
Method method = cl.getDeclaredMethod("clone");
destination = method.invoke(source);
System.out.println("callee - " + destination);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
the output of this program is
callee - {test1=test1, test2=test2, test3=test3}
caller - {}
I hope someone could help me to resolve this problem..
Thanks in advance…
Write the method as a function.
The problem you have with your approach is that you have to create an instance of the desired type so you know what to copy. If you want to pass the desired type as well.
Note: Java does NOT support pass by reference. 😉