In default Java virtual machines each object instance is stored on the heap where its field data is stored together with a reference to its Class
(and a small area used for garbage collection). You are basically asking if you can redefine this link to point to another Class
what is not possible by default.
However, you could hypothetically use sun.misc.Unsafe
to override this reference with a subclass as long as this subclass did not introduce new fields. The outcome of this is however not defined and I would not recommend experimenting with it since the users of your framework could experience very subtle bugs. Also, the sun
package hierarchy is not intended for public use what could break compatibility.
Another way would be offered by the Attach API. You can redefine classes at runtime using a Java agent. This would however effect all instances of a class but from your purpose this would make sence.
Another possibility would be using something like AspectJ to redefine classes before runtime.
Otherwise, you have to return a new instance that works as a proxy for the cache as you are apparently doing it already. This is absolutely okay and an appproach used by major frameworks such as Hibernate. Note that javassist is significantly slower then for example cglib because it reads in class files directly instead of using reflective access in order to avoid class loading. This might break performance when using your cache.