I am using CodeModel to programmatically generate .java files. This is a snippet of code to create a method:
JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");
//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
When I run (assume all other necessary codes are there);
public String getCustomerInfo() { }
But I want to annotate above method like this:
@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }
For which I tried below methods:
method.annotate(...) and method.annotate2(...)
But those methods accept only Class files as a arguments (ie like in the form SomeClass.class), but I want to be able to String as an argument and that class will be available dynamically at run time.
Say I should be able to do like this: method.annotate("Path").
Can anyone help me?
You can use JClass which can be constructed from a String or Class:
JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");
//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
method.annotate(jCodeModel.ref("javax.ws.rs.GET"));
method.annotate(jCodeModel.ref("javax.ws.rs.Path")).param("value", "/getCustomerInfo");
or
method.annotate(jCodeModel.ref(javax.ws.rs.GET));
method.annotate(jCodeModel.ref(javax.ws.rs.Path)).param("value", "/getCustomerInfo");
There's also a variant that takes a JClass, so you have to either:
JCodeModelAs far as I can see, that's pretty much the same approach as with all other uses of classes, I don't see how annotations should be different here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With