I am trying to dynamically generate classes in my application and came across with this limitation/bug? with javassist.
Seems javassist cannot parse the source-body if it has Maps/List with parameterized types.
eg :
public static void main( String[] args ) throws Exception
{
ClassPool pool = ClassPool.getDefault();
CtClass evalClass = pool.makeClass("Eval");
evalClass.addMethod(
CtNewMethod.make("public void test () { java.util.Map<java.lang.String, java.lang.String> tmp=null; }", evalClass));
Class clazz = evalClass.toClass();
Object obj = clazz.newInstance();
Class[] formalParams = new Class[] { };
Method meth = clazz.getDeclaredMethod("test", formalParams);
Object[] actualParams = new Object[] { };
meth.invoke(obj, actualParams);
}
This will give the error
Exception in thread "main" javassist.CannotCompileException: [source error] ; is missing at javassist.CtNewMethod.make(CtNewMethod.java:78) at javassist.CtNewMethod.make(CtNewMethod.java:44)
but when I change the body to
public void test () { java.util.Map tmp=null; }
It works fine. Same applies to "List" .
Any tips? Is this a limitation or a bug ?
As you can read in section 4.7 from Javassist tutorial one of the Javassist's limitations is not supporting the new syntax introduced at J2SE 5.0 (including enums and generics). For future reference, at the concurrent time, javassist is in version 3.20, this information might change in future releases.
This limitation is only when you're using the high level API to write code, if you use low level API (the one you write bytecode directly) you can use generics using the SignatureAttribute. For more information on that please check the answer I gave in Javassist: creating an interface that extends another interface with generics