1package sample;
2
3import javassist.*;
4
5/*
6   A very simple sample program
7
8   This program overwrites sample/Test.class (the class file of this
9   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*/
20public 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.println("g() is already defined in sample.Test.");
32	}
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}
45