Sunday, 3 May 2020

Javassist: Remove a method from an existing class

Follow below steps to remove a method from an existing class.

Step 1: Get ClassPool instance.
ClassPool classPool = ClassPool.getDefault();

Step 2: Get CtClass instace for the class that you want to remove a method.
CtClass testClass = classPool.get("com.sample.app.Test");

Step 3: Get CtMethod instance of the class that you want to remove.
CtMethod sayHelloMethod = testClass.getDeclaredMethod("sayHello");

Step 4: Use removeMethod function to remove the method.
testClass.removeMethod(sayHelloMethod);

Step 5: Publish byte code changes.
testClass.toClass();

Find below working application.

Test.java
package com.sample.app;

public class Test {
    
    public void sayHello() {
        System.out.println("Hello");
    }
    
    public void sayHi() {
        System.out.println("Hi");
    }

}

App.java
package com.sample.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class App {

    public static void main(String args[]) throws Exception {

        ClassPool classPool = ClassPool.getDefault();

        CtClass testClass = classPool.get("com.sample.app.Test");

        CtMethod sayHelloMethod = testClass.getDeclaredMethod("sayHello");
        testClass.removeMethod(sayHelloMethod);

        testClass.toClass();

        Test test = new Test();
        test.sayHi();
        test.sayHello();
    }
}

Run App.java, you will see 'NoSuchMethodError' in console.

Hi
Exception in thread "main" java.lang.NoSuchMethodError: com.sample.app.Test.sayHello()V
    at com.sample.app.App.main(App.java:22)



Previous                                                    Next                                                    Home

No comments:

Post a Comment