3

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.

AndrewBourgeois
  • 2,634
  • 7
  • 41
  • 58
Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
  • 1
    you have a typo: `masterClass` in one case and `masterClazz` in the other. (tangent: why the @#$@#$ does everyone have to use "clazz" with its intentional misspelling, instead of something a little less jarring on the eyes like "cl" or "class1", or even just "class" when it's part of an identifier like "masterClass" or "detailClass" in your case) – Jason S Sep 11 '10 at 00:45
  • @JasonS http://stackoverflow.com/questions/2529974/why-do-java-programmers-like-to-name-a-variable-clazz – jbranchaud Feb 04 '12 at 21:15

1 Answers1

14
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);
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Raoni
  • 166
  • 1
  • 2
  • 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 Sep 11 '10 at 08:02