Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Codemodel - Annotate a method or class

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?

like image 309
Pradeep Simha Avatar asked Mar 26 '26 23:03

Pradeep Simha


2 Answers

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");
like image 180
John Ericksen Avatar answered Mar 28 '26 13:03

John Ericksen


There's also a variant that takes a JClass, so you have to either:

  • have the annotation on your classpath or
  • generate the annotation with the JCodeModel

As 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.

like image 25
Joachim Sauer Avatar answered Mar 28 '26 13:03

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!