How to remove a method using Javassist?

I am trying to remove a method from a class file using a Javassist.

Target class: "RemoveMethod" .

Target Method: "DoubleCheck" .

My codes are:

 package javassist; import java.io.IOException; import java.lang.reflect.Method; import javassist.*; public class cRepair { public static void main(String[] args) throws NotFoundException, IOException, CannotCompileException{ ClassPool pool = ClassPool.getDefault(); CtClass ctClass = pool.get("javassist.RemoveMethod"); CtMethod ctm = ctClass.getDeclaredMethod("DoubleCheck"); ctClass.removeMethod(ctm); ctClass.writeFile("C:/Users/workspace/Javaproject1/src/javassis"); } } 

Then run the code using the javassist.jar file:

 javac -cp javassist.jar cRepair.java 

Then check the target class:

 javap -verbose RemoveMethod.class 

The "DoubleCheck" method still exists!

It looks weird. Why could this happen and how to fix it?

+6
source share
1 answer

Your code reads the bytecode of your class into memory and deletes this method. But it does not write the modified bytecode back to the .class file. You can call CtClass#writeFile() to do this.

+3
source

Source: https://habr.com/ru/post/987357/


All Articles