I started to work with the JCodeModel today. I want to add Attributes with other types than int, String, boolean etc. to my JDefinedClass. The final Java Code built by the JCodeModel should look like:
public Class Team {
private int teamID;
private String teamName;
private Coach coach;
}
How can I add the Field coach with the class type "Coach" with the JCodeModel?
jClass.field(JMod.PRIVATE, *???*, coach);
The second question is: How do I add e.g.
ArrayList<Coach> coachList;
to my attribute List? Thanks
You can simply generate the Coach
class, and pass it as a parameter to the field(...)
method. Note that this method accepts a JType
as the second parameter, and JClass
as well as JDefinedClass
are both inheriting from JType
.
For the ArrayList
, you can define the type parameter by calling narrow
on the defined class, passing in another JType
. (This even works for type parameters - that is, you can even call c.narrow(cm.ref("T"))
to give it a type parameter called T
).
Here is an example:
import java.io.File;
import java.util.ArrayList;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JMod;
public class CodeModelTest
{
public static void main(String[] args) throws Exception
{
JCodeModel codeModel = new JCodeModel();
JDefinedClass teamClass = codeModel._class("Team");
JDefinedClass coachClass = codeModel._class("Coach");
teamClass.field(JMod.PRIVATE, coachClass, "coach");
JClass arrayListClass = codeModel.ref(ArrayList.class);
JClass arrayListOfCoachClass = arrayListClass.narrow(coachClass);
teamClass.field(JMod.PRIVATE, arrayListOfCoachClass, "coaches");
codeModel.build(new File("."));
}
}
It generates the (empty) class Coach
, and the class Team
as
import java.util.ArrayList;
public class Team {
private Coach coach;
private ArrayList<Coach> coaches;
}
(I hope this answer is sufficient. And although the links might die in the future: I found these tutorials very helpful to get a first grip on the CodeModel Edit: Links updated, see below : CodeModel Basics, CodeModel Inheritance)
EDIT: Indeed, the links died. They should only be considered as "supplemental", or as a pointer for further reading. The main information (regarding the original question) should be contained in this answer. I don't have a recommendation for other tutorials (except for what everybody may find with basic websearches), but for now, I replaced the links with their latest snapshots from the web archive.