Java Codemodel - 注释方法或类

Pra*_*mha 3 java sun-codemodel

我正在使用CodeModel以编程方式生成.java文件.这是创建方法的代码片段:

JCodeModel jCodeModel = new JCodeModel();
JDefinedClass definedClass = jCodeModel._class("Foo");

//To generate method
JMethod method = definedClass.method(3, String.class, "getCustomerInfo()");
Run Code Online (Sandbox Code Playgroud)

当我跑(假设所有其他必要的代码都在那里);

public String getCustomerInfo() { }
Run Code Online (Sandbox Code Playgroud)

但是我想要注释上面这样的方法:

@GET
@Path("/getCustomerInfo")
public String getCustomerInfo() { }
Run Code Online (Sandbox Code Playgroud)

我试过以下方法: method.annotate(...) and method.annotate2(...)

但是这些方法只接受Class文件作为参数(比如SomeClass.class形式),但我希望能够将String作为参数,并且该类将在运行时动态可用.

说我应该能够这样做:method.annotate("Path").

谁能帮我?

Joh*_*sen 6

您可以使用JClass可以从String或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");
Run Code Online (Sandbox Code Playgroud)

要么

method.annotate(jCodeModel.ref(javax.ws.rs.GET));
method.annotate(jCodeModel.ref(javax.ws.rs.Path)).param("value", "/getCustomerInfo");
Run Code Online (Sandbox Code Playgroud)