使用JAX-RS(泽西岛)从名称获取枚举值
题
我发现很难将确切的问题放入单词中,所以我会举个例子。
我有一个休息服务,它允许通过为每个的链接创建链接来查看所有可用枚举。这有效。
但现在我需要找到一种方法来在json中显示具体枚举值,当点击提供一个链接时。
enumresource.class:
@Path("/enums")
public class EnumsResource
{
public EnumsResource()
{
}
@SuppressWarnings("rawtypes")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response enums(@Context
UriInfo info){
List<Class> resourceClasses = getAllResourceClasses();
List<Link> enumLinks = new ArrayList<Link>();
String contextPath = Link.getFullyQualifiedContextPath(info);
for (Class clazz : resourceClasses)
{
for (Field field : clazz.getDeclaredFields())
{
if (field.getAnnotation(Enumerated.class) != null)
{
Link link = new Link(contextPath+"/enums/", field.getName());
enumLinks.add(link);
}
}
}
RestResponseMetadata metadata = new RestResponseMetadata(200, 200000);
RestResponse response = new RestResponse(metadata, enumLinks);
return Response.ok().entity(response).build();
}
@SuppressWarnings("rawtypes")
@GET
@Path("/{enum}")
@Produces(MediaType.APPLICATION_JSON)
public Response enums(@PathParam("enum") String enumName){
????
}
@SuppressWarnings("rawtypes")
private List<Class> getAllResourceClasses()
{
List<Class> classes = new ArrayList<Class>();
for (ResourcePath path : ResourcePathProvider.getInstance().getAllResourcePaths())
{
classes.add(path.getAssociatedClass());
}
return classes;
}
}
.
以下是调用“/枚举”后的JSON响应的示例:
{
"metadata":{
"code":200,
"errorCode":200000,
"userMessage":null,
"developerMessage":null
},
"content":[
{
"href":"http://localhost:8080/source/api/enums/status"
},
{
"href":"http://localhost:8080/source/api/enums/role"
},
{
"href":"http://localhost:8080/source/api/enums/license"
},
{
"href":"http://localhost:8080/source/api/enums/selectedLicense"
}
}
.
任何想法如何实现如何?每个答案都非常感谢。
谢谢。
解决方案
这就是我如何做到的:
Map<String, Class<Enum>> map = ... //Map <Enum name, Enum class>
@SuppressWarnings("rawtypes")
@GET
@Path("/{enum}")
@Produces(MediaType.APPLICATION_JSON)
public Response enums(@PathParam("enum") String enumName){
Class c = map.get(enumName);
if(c!=null) {
for(Enum e : c.getEnumConstants() {
LOGGER.info(e);
}
}
}
.
如jb nizet所示,您也可以预期接收枚举的完全限定名称。在这种情况下,忘记地图并使用反射来获取枚举类。
不隶属于 StackOverflow