aboutsummaryrefslogtreecommitdiffstats
path: root/src/test/javassist/HotswapTest.java
blob: deab8fadf07c12ae263f0d1fda3bb4615e796ee1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package javassist;

import javassist.util.HotSwapAgent;
import junit.framework.TestCase;

public class HotswapTest extends TestCase {
    public static void main(String[] args) throws Exception {
        // run java -javaagent:hotswap.jar javassist.HotswapTest
        new HotswapTest(HotswapTest.class.getName()).testHotswap();
    }

    public HotswapTest(String name) {
        super(name);
    }

    public static class Foo {
        public int foo() { return 1; }
    }

    public void testHotswap() throws Exception {
        if (javassist.bytecode.ClassFile.MAJOR_VERSION
            >= javassist.bytecode.ClassFile.JAVA_9)
            return;

        Foo f = new Foo();
        assertEquals(1, f.foo());

        ClassPool cp = ClassPool.getDefault();
        CtClass clazz = cp.get(Foo.class.getName());
        CtMethod m = clazz.getDeclaredMethod("foo");
        clazz.removeMethod(m);
        clazz.addMethod(CtNewMethod.make("public int foo() { return 2; }", clazz));
        HotSwapAgent.redefine(Foo.class, clazz);
        Foo g = new Foo();
        assertEquals(2, g.foo());
        System.out.println("Foo#foo() = " + g.foo());
    }
}