01: package sample;
02:
03: import javassist.*;
04:
05: /*
06: A very simple sample program
07:
08: This program overwrites sample/Test.class (the class file of this
09: class itself) for adding a method g(). If the method g() is not
10: defined in class Test, then this program adds a copy of
11: f() to the class Test with name g(). Otherwise, this program does
12: not modify sample/Test.class at all.
13:
14: To see the modified class definition, execute:
15:
16: % javap sample.Test
17:
18: after running this program.
19: */
20: public class Test {
21: public int f(int i) {
22: return i + 1;
23: }
24:
25: public static void main(String[] args) throws Exception {
26: ClassPool pool = ClassPool.getDefault();
27:
28: CtClass cc = pool.get("sample.Test");
29: try {
30: cc.getDeclaredMethod("g");
31: System.out
32: .println("g() is already defined in sample.Test.");
33: } catch (NotFoundException e) {
34: /* getDeclaredMethod() throws an exception if g()
35: * is not defined in sample.Test.
36: */
37: CtMethod fMethod = cc.getDeclaredMethod("f");
38: CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null);
39: cc.addMethod(gMethod);
40: cc.writeFile(); // update the class file
41: System.out.println("g() was added.");
42: }
43: }
44: }
|