1 Reply Latest reply on Oct 10, 2007 5:46 PM by ssiddiqu

    java.lang.NoSuchMethodException when invoking a method

    ssiddiqu

      I am getting java.lang.NoSuchMethodException when running the following code. Any ideas how can I create a new class, add a method and invoke it?


      String aMethod="printSomething";
      String src="public static void "+aMethod+"()" +
      "{" +
      "System.out.println(\"Kia Hoa\");" +
      "}";
      System.out.println(src);
      String className="mytest.MyTest";

      // we assume that called methods have no argument
      Class<?> params[] = {};
      Object paramsObj[] = {};
      try
      {
      ClassPool pool = ClassPool.getDefault();
      CtClass cc = pool.makeClass(className);
      CtNewMethod.make(src,cc);
      cc.stopPruning(true);
      //cc.freeze();
      Loader cl = new Loader(pool);

      // Class<?> thisClass = Class.forName(className);
      Class thisClass = cl.loadClass(className);
      // get the method
      Method thisMethod = thisClass.getDeclaredMethod(aMethod);
      // call the method
      System.out.println
      (thisMethod.invoke(thisClass, paramsObj).toString());


      }
      catch(Exception e)
      {
      e.printStackTrace();
      }

        • 1. Re: java.lang.NoSuchMethodException when invoking a method
          ssiddiqu

          Can some more experienced users please help me on this?
          Thanks.
          --Sarim.

          "ssiddiqu" wrote:
          I am getting java.lang.NoSuchMethodException when running the following code. Any ideas how can I create a new class, add a method and invoke it?


          String aMethod="printSomething";
          String src="public static void "+aMethod+"()" +
          "{" +
          "System.out.println(\"Kia Hoa\");" +
          "}";
          System.out.println(src);
          String className="mytest.MyTest";

          // we assume that called methods have no argument
          Class<?> params[] = {};
          Object paramsObj[] = {};
          try
          {
          ClassPool pool = ClassPool.getDefault();
          CtClass cc = pool.makeClass(className);
          CtNewMethod.make(src,cc);
          cc.stopPruning(true);
          //cc.freeze();
          Loader cl = new Loader(pool);

          // Class<?> thisClass = Class.forName(className);
          Class thisClass = cl.loadClass(className);
          // get the method
          Method thisMethod = thisClass.getDeclaredMethod(aMethod);
          // call the method
          System.out.println
          (thisMethod.invoke(thisClass, paramsObj).toString());


          }
          catch(Exception e)
          {
          e.printStackTrace();
          }