/Users/lyon/j4p/src/javassist/sample/Test.java

1    package javassist.sample; 
2     
3    import javassist.*; 
4     
5    import java.util.Collection; 
6    import java.util.Iterator; 
7     
8    /* 
9       A very simple sample program 
10    
11      This program overwrites sample/Test.class (the class file of this 
12      class itself) for adding a method g().  If the method g() is not 
13      defined in class Test, then this program adds a copy of 
14      f() to the class Test with name g().  Otherwise, this program does 
15      not modify sample/Test.class at all. 
16    
17      To see the modified class definition, execute: 
18    
19      % javap sample.Test 
20    
21      after running this program. 
22   */ 
23    
24   public class Test { 
25       public int f(int i) { 
26    
27           return i + 1; 
28       } 
29    
30    
31       public static void main(String[] args) throws Exception { 
32           ClassPool cp 
33                  = ClassPool.getDefault(null); 
34    
35           CtClass cc = cp.get("javassist.sample.Test"); 
36           System.out.println("getbytecodes:"); 
37           byte b[] = cc.toBytecode(); 
38           System.out.println("bytes in code="+b.length); 
39           System.out.println("refs="); 
40           printClassRefs(cc); 
41    
42           try { 
43               cc.getDeclaredMethod("g"); 
44               System.out.println("g() is already defined in sample.Test."); 
45           } catch (NotFoundException e) { 
46               /* getDeclaredMethod() throws an exception if g() 
47                * is not defined in sample.Test. 
48                */ 
49               CtMethod fMethod = cc.getDeclaredMethod("f"); 
50               //CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null); 
51               //cc.addMethod(gMethod); 
52               //cp.writeFile("sample.Test");  // update the class file 
53               //System.out.println("g() was added."); 
54           } 
55       } 
56    
57       private static void printClassRefs(CtClass cc) { 
58           Collection c = cc.getRefClasses(); 
59           try { 
60               Iterator i = c.iterator(); 
61               while (i.hasNext()) { 
62                   System.out.println 
63                           ((String) i.next()); 
64               } 
65           } catch (Exception e) { 
66               e.printStackTrace(); 
67    
68           } 
69       } 
70   } 
71