zackim
zackim

Reputation: 11

how to transform interface to abstract by using javassist

I am using javassist library for modify class files.

I want to modify interface to abstract class

for example, original :

public interface javax.servlet.Servlet {
 public void init(ServletConfig config) throws ServletException;
} 

modified :

public abstract javax.servlet.Servlet {
    public void init(ServletConfig config) throws ServletException {
        System.out.println(config.getServletContext().getServerInfo());
        callMethod(); // this is implemented original method
    }
} 

How can i apply this solution like aop(before, after)?

Upvotes: 0

Views: 141

Answers (1)

rakwaht
rakwaht

Reputation: 3967

I think the first problem with your approach is that when you try to modify your interface using Javassist you are attempting to redefine an interface that has been already loaded by the class loader.

One option might be to do a bit of classloader tricks: create a new classloader that doesn't have your existing interface loaded (parent is the system classloader) and have Javassist load through that (use aCtClass.toClass() method that takes a ClassLoader argument). However is not really something I would do since to manage properly more than one ClassLoader is not that easy.

There might be a better way to achieve your goal, and creating new classes might be a better design. You could create a new class that implements everything you need and then extends the required interface.

Moreover I suggest you to take also a look at dynamic proxies that could be an option as well. Their biggest advantage is that you don't need any 3rd party libraries to create them.

Upvotes: 1

Related Questions