Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a method using Javassist?

Tags:

java

javassist

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

Target class:"RemoveMethod".

Target method:"DoubleCheck".

My codes:

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 file "javassist.jar":

javac -cp javassist.jar cRepair.java

Then check the target class:

javap -verbose RemoveMethod.class

The method "DoubleCheck" is still there!

This looks really odd. Why could this happen and how to fix it?

like image 259
Delibz Avatar asked May 17 '15 04:05

Delibz


People also ask

What is Javassist used for?

Javassist (Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it.

What is ClassPool in Java?

public class ClassPool extends java.lang.Object. A container of CtClass objects. A CtClass object must be obtained from this object. If get() is called on this object, it searches various sources represented by ClassPath to find a class file and then it creates a CtClass object representing that class file.


1 Answers

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

like image 136
Stefan Ferstl Avatar answered Sep 21 '22 02:09

Stefan Ferstl