Dealing with generic fields in JCodeModel
A nother article about JCodeModel. This time we will make a short excursion about how to generate generic fields in JCodeModel.
I recently wrote an article about generating enums with JCodeModel. Due to the lack of documentation of JCodeModel using it can become very time consuming. I had to put in a lot of time to research a lot of basic stuff. This article will show you how to declare and assign generic fields.
As before to get started you have to create an instance of JCodeModel. You will need this object to generate your classes.
Creating a class
To create a class you need a package where the class is located. Package names can be specified as usual. JCodeModel will automcatically create the corresponding structure during code generation.
In case you do not want to declare a package, you can also generate a class using the root code model.
Declaring the field type
Building a class to declare fields is straightforward and can be done by referencing it with an instance of JCodeModel.
Declaring generic types can be done by using the narrow method.
You can even create nested generics like
Map<String, List<String>> by nesting the narrow method.
Using generic wildcards
When using generics you soon want to get into using wildcards. To create a generic type simply reference a class using the JCodeModel instance and call the wildcard method. You can specify the wildcard type with the EWildcardBoundMode enum.
Creating and setting the field
Starting with Java 7 there is no need to declare an instances generic type when you already declared it in the fields definition. Just let the angle brackets stay empty. To achieve it in JCodeModel put an empty list into the narrow method.
Building the file
Simply define an output folder and let the model genearate your code. All the classes, folders and packages you declared earlier will be generated for you.
JCodeModel will generate the following ready to use class for you.
JCodeModel is a nice framework, but lacks some solid documentation. I hope this article will help you to generate your own Java classes without crawling through the framework’s JavaDoc or codebase. You can check out he whole example code on Github.