Search code examples
javajavassist

How do I remove the body of a method or constructor with javassist?


I need to remove the body of constructors and methods w/ a void return type using the javassist library. The following works.

ctClass.getConstructors()[0].setBody("int i = 0");

But this doesn't

ctClass.getConstructors()[0].setBody("");

Instead I get this exception

compile error: syntax near ""

When I try

ctClass.getConstructors()[0].setBody(null);

I get

compiler error: no such a constructor

I get the same error when trying to empty a method w/ void return type. Looking through Google and documentation, I can't figure out how to empty out the body without inserting some kind of code and I don't want to add arbitrary code for no reason.


Solution

  • Javassist replaces a method body with a valid block as the body of a method. A non-statement is not a valid block. You can instead set { } as the method body which is a block. Alternatively, you could also make the implicit return; statement explicit.

    For a constructor, it is always required to invoke the super costructor or an auxiliary constructor first. An empty block would not be valid.