我在使用javaassist时遇到了一些麻烦。我试图动态生成课程,但我收到的错误是:
no such class: Foo
在下面generateFooMethod
步骤的编译步骤中。任何人都可以帮助我吗?
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
}
我还尝试在方法声明中明确引用Foo,如下所示:
sb.append("public static com.amir.Foo " +methodName+ "(com.amir.Foo foo) {");
也不起作用。