I am using ASM's ClassWriter to duplicate a class. I use reflection to load a class with this duplicated byte code, however when I try to invoke a method of the duplicate class with an instance of the class that was duplicated I get an 'Object is not an instance of declaring class' exception.
Object originalObj = ...
Class<?> originalClass = obj.getClass();
String methodName = ...
ClassReader cr = new ClassReader(originalClass.getName());
ClassWriter cw = new ClassWriter(0);
cr.accept(cw, 0);
DynamicClassLoader loader = new DynamicClassLoader();
Class<?> c = loader.define(originalClass.getName(), cw.toByteArray());
Method m = c.getMethod(methodName); // Assume 'methodName' has no args
m.setAccessible(true);
m.invoke(originalClass.cast(originalObj));
DynamicClassLoaderand how it's interpretation of this new class differs from the original. Try loading both classes inDynamicClassLoaderand see if it recognises them as the same class...