Get Enum values from its name using JAX-RS (Jersey)
Question
I find it difficult to put the exact question into words, so I'll just give an example.
I have a REST service which allows to view all available Enums by creating a link for each of them. This works OK.
But now I need to find a way to display a concrete Enum values in JSON when one of the provided links is clicked.
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;
}
}
Here's an example of JSON response after calling "/enums":
{
"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"
}
}
Any ideas how this can be achieved? Every answer is highly appreciated.
Thank you.
Solution
This is how I would do it :
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);
}
}
}
As suggested by JB Nizet, you could also expect to receive the fully qualified name of the enum. In this case, forget the map and use reflection to get the enum class.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow