title: Use cglib BeanCopier with multiple classloaders
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>The issue is that cglib BeanCopier doesn't work in this case. The simplest code to show it is:</p>
  
  <pre class="lang-java prettyprint-override"><code>URL classesUrl = new File("/directory/with/class-files-for-Person").toURL();
  Class&lt;?&gt; c1 = new URLClassLoader(new URL[] {classesUrl}).loadClass("Person");
  Class&lt;?&gt; 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);
  </code></pre>
  
  <p>It gives the exception: </p>
  
  <pre><code>Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to Person
  at net.sf.cglib.empty.Object$$BeanCopierByCGLIB$$da60538e.copy(&lt;generated&gt;)
  at Main.main(Main.java:22)
  </code></pre>
  
  <p>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).</p>