views:

44

answers:

1

Using com.sun.codemodel, I would like to generate a generic LinkedList field. I can create a raw field using this code:

JDefinedClass masterClass;
String detailName;
JDefinedClass detailClass;
JFieldVar detailField = masterClass.field(JMod.PRIVATE, LinkedList.class, detailName);

But I could not find a way to create a LinkedList with a generic type of detailClass.

A: 

JClass detailClass = codeModel.ref(String.class);

String detailName = "myLinkedListField";

JClass rawLLclazz = codeModel.ref(LinkedList.class);

JClass fieldClazz = rawLLclazz.narrow(detailClass);

JFieldVar detailField = def.field(JMod.PRIVATE, fieldClazz, detailName);

Raoni
Thanks, this worked. I somehow glanced over the doc for `narrow` since it looked like a typecast like in `javax.rmi.PortableRemoteObject.narrow`.
Jörn Horstmann