Java Codemodel-注释方法或类 [英] Java Codemodel - Annotate a method or class

查看:74
本文介绍了Java Codemodel-注释方法或类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() { }

为此,我尝试了以下方法: method.annotate(...) and method.annotate2(...)

For which I tried below methods: method.annotate(...) and method.annotate2(...)

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

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.

说我应该可以这样做:method.annotate("Path").

Say I should be able to do like this: method.annotate("Path").

有人可以帮助我吗?

推荐答案

您可以使用JClass,它可以由字符串或类构造:

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");

method.annotate(jCodeModel.ref(javax.ws.rs.GET));
method.annotate(jCodeModel.ref(javax.ws.rs.Path)).param("value", "/getCustomerInfo");

这篇关于Java Codemodel-注释方法或类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆