ROM*_*eer 12 java annotations enunciate code-documentation type-hinting
我有一些REST服务(使用和生成application/json),我用它@TypeHint来生成文档.
现在我有这样的事情:
import javax.ws.rs.core.Response;
...
@Path("/path")
public class MyClass {
@GET
@TypeHint(MyResponse.class)
public Response getIt() {
MyResponse resp = ... ;
return MyBuilder.build(resp);
}
}
Run Code Online (Sandbox Code Playgroud)
但是MyResponse是一个包装List<MyType>.
我的build方法MyResponse看起来像这样:
public static Response build(Serializable payload) {
return Response.ok(msr).header(...).build();
}
Run Code Online (Sandbox Code Playgroud)
我想直接使用List<MyType>而不是MyResponse.TypeHint在以下代码中使用哪种方法最好?
@GET
@TypeHint(/* TODO */)
public Response getIt() {
List<MyType> myList = ... ;
return MyBuilder.build(myList);
}
Run Code Online (Sandbox Code Playgroud)
我在考虑以下选项:
@TypeHint(List.class)@TypeHint(MyType.class)@TypeHint(List<MyType>.class) - >遗憾的是,由于Java类型擦除,这不起作用.题:
3号有没有有效的替代方案?
即使类型是a List,数字1也没用,因为我自己的类型必须注释@XmlRootElement并且不可List更改(它来自JDK).
对于2号有一种解决方法,但它并不完美:
指定它是ListJavadoc中的一个(例如:在@return单词之后)(可以通过HTML标记使用粗体,颜色,斜体等来强调它)
例如:
/**
* ...
* @return <strong><font color="blue">List<MyType></font></strong>
*/
Run Code Online (Sandbox Code Playgroud)细节:
小智 5
在使用 TypeHint 而不是 List.class 时,我选择使用 MyType[].class。这样,文档将说明“MyType 数组”对于我的带有 json 的 rest-api 来说是正确的。
@TypeHint(value = MyType[].class)
Run Code Online (Sandbox Code Playgroud)
如您所知,TypeHint用于给出有关 JAX-RS资源方法返回或接受什么作为输入参数的提示。
在您的情况下,正在描述返回类型。
我假设 ClassReturnedByMyBuildersBuildMethod 是 javax.ws.rs.core.Response 抽象类的子类。对于您展示的代码,您需要使用的是 MyBuilder 的 build 方法返回的类 - @TypeHint(ClassReturnedByMyBuildersBuildMethod.class)。
选项 2 @TypeHint(MyType.class) 没有意义。它不是返回类型,也不是输入参数。
更新 1:通过您的解决方法,它可能有意义:)
如果您向 getIt 方法添加输入参数 - 就像public Response getIt(List<MyType> myList){...您将使用选项 1( @TypeHint(List.class)) 一样,因为您知道org.codehaus.enunciate.jaxrs.TypeHint注释类型元素声明具有Class返回类型 ( Class<?> value();) 并且您不能使用参数化类型,因为删除了泛型类型(在本例中,参数化类型在运行时共享相同的类 - List)。
但是将输入参数更改为getIt(List<MyType> myList) 可能不可行,因为必须从 URI 获取列表(使用 javax.ws.rs 的 @QueryParam 或 @Context UriInfo )。如果您可能担心的话,此问题将解决使用参数列表作为输入时的最佳实践。
更新 2:由于 XmlRootElement 约束,选项 1 变得不太可行。
更新 3:我认为使用 TypeHint 注释的选项 3 没有有效的替代方案。
您必须采用自定义选项 2 解决方法。