2
votes

Is it possible to move/copy a method from one class to another with Javassist?

public class A {
    public static void test() {
        System.out.println("hello world");
    }
}

public class B {
    // add test() here
}

What I've tried:

ctClassB.addMethod(ctClassA.getDeclaredMethod("test"));

This results in an exception: javassist.CannotCompileException: bad declaring class.

Looking at the Javassist javadocs, I don't believe this is possible, but is there some way to change the declaring class of the method?

1

1 Answers

0
votes

Constructing a new CtMethod appears to be working:

CtMethod method = ctClassA.getDeclaredMethod("test");
ctClassB.addMethod(new CtMethod(method, ctClassB, null));