1

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){}
Moon Mysterious
  • 164
  • 1
  • 14

1 Answers1

0

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));
rsutormin
  • 1,629
  • 2
  • 17
  • 21
  • Now support I have List of Employee object, if I code like below it is not importing Employee class(import com.Employee is not adding) `JClass jObjType = ((JClass) jcodemodel._ref(GenericEntity.class)).narrow(jcodemodel.ref(List.class).narrow( jcodemodel.ref(Employee.class))); JVar jvobj = jMethodResource.body().decl(jcodemodel.ref(Object.class), "obj", JExpr._new(jcodemodel.anonymousClass(jObjType)).arg(JExpr.direct("listStr")));` Any solution please? – Moon Mysterious Sep 14 '15 at 11:47
  • It looks like there is some issue in JCodeModel with generic type importing. If you explicitly declare variable of List type it fixes import problem. So why don't you accept my answer and we can discuss your further issues in comments? – rsutormin Sep 14 '15 at 18:25
  • Sorry, my bad. I click, but missed by my bad mouse :). Yeah, I did what you say. It just having an used variable. Thanks a ton. You really save my few hours effort. – Moon Mysterious Sep 15 '15 at 06:30