0

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.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
  • Which JDK/JRE version are you using? also, Which javaassist version? – morgano Oct 23 '14 at 23:14
  • JDK 7 update 55, and I forget which javaassist version. Can that affect this behavior? – Amir Afghani Oct 23 '14 at 23:21
  • I had a similar problem when I migrated from JDK 6 to 7, it had to do with the stack map frames, try using `-XX:-UseSplitVerifier` when running your application, if this time it runs Ok then you will need a more recent version of javassist (I don't post this as an answer because I'm not sure this is your problem, if so, then Google about the relatively new mechanism for class validations that is now compulsory in java 8, i. e. `-XX:-UseSplitVerifier` is deprecated now) – morgano Oct 23 '14 at 23:46

0 Answers0