I'd like to copy one bean to another in Java. The problem that it is inside classloading-juggler framework and both classes are loaded by different classloaders which also differs from the current classloader.
It is required to do it in most efficient way, so the best way is to use bytecode generation solutions (like cglib BeanCopier), but not reflection-based.
The issue is that cglib BeanCopier doesn't work in this case. The simplest code to show it is:
URL classesUrl = new File("/directory/with/class-files-for-Person").toURL();
Class<?> c1 = new URLClassLoader(new URL[] {classesUrl}).loadClass("Person");
Class<?> c2 = new URLClassLoader(new URL[] {classesUrl}).loadClass("Person");
Object o1 = c1.newInstance();
Object o2 = c2.newInstance();
BeanCopier copier = BeanCopier.create(o1.getClass(), o2.getClass(), false);
copier.copy(o1, o2, null);
It gives the exception:
Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Person
at net.sf.cglib.empty.Object$$BeanCopierByCGLIB$$da60538e.copy(<generated>)
at Main.main(Main.java:22)
I'm finding the way to resolve it. In my case both classes are the same but loaded with custom classloaders. Also the properties contain only privimives and classes from java.* (so they are loaded by standard classloader).