Search code examples
javajcodemodel

Does Java codemodel support GenericEntity


Does Java codemodel support GenericEntity ?

I am trying to generate a code like below using jcodemodel:

Object obj = new GenericEntity<List<java.lang.String>>(listStr){}

But I am not able do that. I used below code :

JType jObjType = ((JClass) jcodemodel._ref(GenericEntity.class)).narrow(jcodemodel.ref(List.class).narrow(
                jcodemodel.ref(String.class)));
JVar jvobj = jMethodResource.body().decl(jcm.ref(Object.class), "obj",  JExpr._new(jObjType).arg(.....listStr reference...));

The code obtained using this is as follows : Object obj = new GenericEntity>(listStr)

But "{}" is missing.

Can anyone help me here? How do a code so that I am obtained with {} :

Object obj = new GenericEntity<List<java.lang.String>>(listStr){}

Solution

  • Use this method (https://codemodel.java.net/nonav/apidocs/com/sun/codemodel/JCodeModel.html#anonymousClass(com.sun.codemodel.JClass)). Something like that:

        JClass listOfEmplType = jcodemodel.ref(List.class).narrow(jcodemodel.ref(
                Emplyee.class.getName()));
        JVar listOfEmpl = jMethodResource.body().decl(listOfEmplType, "listStr", JExpr._null());
        JClass jObjType = ((JClass) jcodemodel._ref(GenericEntity.class)).narrow(listOfEmplType);
        JVar jvobj = jMethodResource.body().decl(jcodemodel.ref(Object.class), "obj",  
                JExpr._new(jcodemodel.anonymousClass(jObjType)).arg(listOfEmpl));