I am creating a Proxy class using Javassist ProxyFactory with the following code:
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(entity.getClass());
factory.setInterfaces(new Class[] { MyCustomInterface.class });
.....
Class clazz = factory.createClass();
Object result = clazz.newInstance();
The problem is that I also need to add a field to the class. But if I do CtClass proxy = ClassPool.getDefault().get(clazz.getName());
it gaves a NotFoundException
How can I add a field the class created with createClass? Is there a better way to do what I am trying to do?
This is based in your reply to my comment.
You can indeed use
MyCustomInterface
and your proxyClass to create sort of a mixin in Java. But you'll still have to cast from proxy class toMyCustomInterface
to be able to call the methods.Let's get started.
Creating your proxy
First you create your proxy has you already were doing:
Method handler: Doing the magic
Javassist proxies allow you to add a MethodHandler. It basically acts has a an InvocationHandler would in a regular Java Proxy, that means it works as a method interceptor.
The method handler will be your mixin! First you create a new MethodHandler with the custom field you actually want to add to the class, along with the entity object you've started proxying:
(*) Notice that even if I say in the comment to handle the call internally you can have the interface implementation in another place that isn't your method handler and just call it from here.
Getting everything together
You should now be able to do
((MyCustomInterface)proxyEntity).someMethodFromTheInterface()
and let it be handled by yourCustomMethodHandler
Summing up
Keep in mind that these approach isn't perfect, being one of the short comings the code in Entity class cannot refer to the interface unless you first create the proxy.
If anything wasn't very clear for you, just comment and I'll do my best to clarify you.