1 Reply Latest reply on Sep 25, 2003 7:15 AM by Shigeru Chiba

    Loading classes dynamically

    fredjones Newbie

      I want to be able to modify class at load time, but everything I try doesn't seem to work. I've tried reading the tutorial and doing what it says to, but I don't seem to have any luck. No matter what I do, the original unmodified class is loaded.

      Here is what I am trying:

      ClassPool pool = ClassPool.getDefault();
      String className = "Foo";
      CtClass cc = pool.get(className);

      cc.defrost();
      CtMethod m = new CtMethod(CtClass.voidType, "bar", new CtClass[] {}, cc);
      cc.addMethod(m);

      Loader cl = new Loader(pool);
      cl.delegateLoadingOf(className);
      cl.loadClass(className);

      Foo foo = new Foo();
      Class fooClass = foo.getClass();
      Method[] methods = fooClass.getMethods();
      for (int i = 0; i < methods.length; i++) {
      System.out.println("Method:" + methods.getName());
      }

      When I run this, "bar" is not one of the methods on Foo. What am I doing wrong???

      Thanks,

      Fred

        • 1. Re: Loading classes dynamically
          Shigeru Chiba Expert

          > Loader cl = new Loader(pool);
          > cl.delegateLoadingOf(className);

          Well, this lets the system class loader load
          "className" from the disk. Thus the unmodified
          class will be loaded.

          If the above line is removed,

          > cl.loadClass(className);

          This call should return the java.lang.Class object
          representing the modified class.

          > Foo foo = new Foo();

          But this statement lets the system class loader load
          the unmodified class.

          A key thing is that you have to use javassist.Loader
          for loading the modified class.