I am having some trouble with javaassist. I'm attempting to generate a class on the fly and I'm getting an error that says:
no such class: Foo
during the compilation step in the generateFooMethod
step below. Can anyone help me?
try {
final ClassPool pool = ClassPool.getDefault();
pool.importPackage("com.amir"); // <-- foo exists here
final CtClass ctClass = pool.makeClass(className);
ctClass.addMethod(generateFooMethod(ctClass, methodName));
return ctClass.toClass();
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("compile failed");
}
}
private static CtMethod generateFOOMethod(final CtClass declaringClass,
final String methodName)
throws CannotCompileException {
final StringBuilder sb = new StringBuilder();
sb.append("public static Foo " +methodName+ "(Foo foo) {");
sb.append(" return foo");
sb.append("}");
return CtMethod.make(sb.toString(), declaringClass); // <-- failure happens here
}
I've also tried explicitly referring to Foo in the method declaration as in:
sb.append("public static com.amir.Foo " +methodName+ "(com.amir.Foo foo) {");
which also does not work.