You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Test.java 1.2KB

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