Search code examples
javajavassist

Is it possible to proxy or replace a static method with javassist


I've tried various methods but have been unable to get this to work. I also have been unable to locate a definitive answer.

If this is possible a simple example would be appreciated


Solution

  • Yes, you can of course replace the body of any static method. This is one of the most common use cases:

    ClassPool cp = new ClassPool(true);
    CtClass ctClass = cp.get("com.acme.Foo");
    CtMethod ctMethod = ctClass.getDeclaredMethod("bar");
    ctMethod.setBody("{ }");
    ctClass.toClass();
    

    What you cannot do is to use the proxy utilities that are similar to the Java proxy invocationhandler to do so. The latter utility relies on virtual override which does not allow handling static methods.