If you have an enum like:
public enum AnimalType {
BIG_BIRD,
SMALL_CAT,
MEDIUM_DOG;
}
then in order for JAX-RS to know what instance to return, your query parameter must be ?animal=BIG_BIRD
, ?animal=SMALL_CAT
or ?animal=MEDIUM_DOG
.
The value of the query parameter is fed to the valueOf
static method of the enum to get an instance. Off course, if you send something else like bird
it won't match anything and it won't work because @QueryParam
expects this:
The type T of the annotated parameter, field or property must either:
- Be a primitive type
- Have a constructor that accepts a single String argument
- Have a static method named valueOf that accepts a single String argument (see, for example, Integer.valueOf(String))
- Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.
The same applies for the @DefaultValue
also. You have to specify @DefaultValue("BIG_BIRD")
, @DefaultValue("SMALL_CAT")
or @DefaultValue("MEDIUM_DOG")
:
@POST
@Path("/zoo")
public Response createNewAnimal(
@QueryParam("animal")
@DefaultValue("SMALL_CAT") AnimalType type) {
// ...
return Response.ok().entity(type.toString()).build();
}
If you don't want to expose the names on your Java types to the client, you can transform the proper query string value into an enum instance. An if ... else ... if is a very simple way to achieve this but if you want something fancier you could create a wrapper like this:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class AnimalTypeWrapper {
private static final Map<String, AnimalType> MAPPER = Collections
.unmodifiableMap(new HashMap<String, AnimalType>() {
{
put("bird", AnimalType.BIG_BIRD);
put("dog", AnimalType.MEDIUM_DOG);
put("cat", AnimalType.SMALL_CAT);
}
});
private AnimalType type;
public static AnimalTypeWrapper valueOf(String value) {
AnimalType type = AnimalTypeWrapper.MAPPER.get(value.toLowerCase());
if (type == null) {
// if nothing found just set the desired default value
type = AnimalType.SMALL_CAT;
}
return new AnimalTypeWrapper(type);
}
private AnimalTypeWrapper(AnimalType type) {
this.type = type;
}
public AnimalType getType() {
return this.type;
}
}
and in your resource method have:
@POST
@Path("/zoo")
public Response createNewAnimal(
@QueryParam("animal")
AnimalTypeWrapper typeWrapper) {
// ...
AnimalType type = typeWrapper.getType();
return Response.ok().entity(type.toString()).build();
}