0

Whenever I create a new method with Javassist using this method

public static void addMethod(CtClass targetClass, String code) throws Exception {
    CtNewMethod.make(code, targetClass);
    targetClass.toClass();
    logger.info("Method Successfully created in " + targetClass.getName());
}

and later try to invoke it with

public static void invokeMethod(CtClass targetClass, String methodName, Object...args) throws Exception {
    Method method = targetClass.getClass().getDeclaredMethod(methodName);
    method.invoke(targetClass, args);
}

I get the exception "java.lang.NoSuchMethodException: javassist.CtClassType.testMethod()"

does anyone know what I'm doing wrong?

1 Answers1

0

The error is thrown because with
Method method = targetClass.getClass().getDeclaredMethod(methodName);
you are invoking getClass() on a CtClass object but you should invoke on class generated by targetClass.toClass().
You have to restructure your code in this way:

CtClass targetClass = new CtClass();
addMethod(targetClass, method1Code);
addMethod(targetClass, method2Code);
Class<?> k = targetClass.toClass();
invokeMethod(k, ...);

and rewrite

  1. addMethod() removing targetClass.toClass()
  2. Change invokeMethod()'s first param with a standard java.lang.Class
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69