Java Reference
In-Depth Information
a specific Java type. You can also define default values for an injection parameter when an
item does not exist in the request. Finally, you can work with encoded strings directly, rather
than having JAX-RS automatically decode values for you. Let's look into a few of these.
Automatic Java Type Conversion
All the injection annotations described in this chapter reference various parts of an HTTP re-
quest. These parts are represented as a string of characters within the HTTP request. You are
not limited to manipulating strings within your Java code, though. JAX-RS can convert this
string data into any Java type that you want, provided that it matches one of the following
criteria:
1. It is a primitive type. The
int
,
short
,
float
,
double
,
byte
,
char
, and
boolean
types
all fit into this category.
2. It is a Java class that has a constructor with a single
String
parameter.
3. It is a Java class that has a static method named
valueOf()
that takes a single
String
argument and returns an instance of the class.
4. It is a
java.util.List<T>
,
java.util.Set<T>
, or
java.util.SortedSet<T>
,
where
T
is a type that satisfies criteria 2 or 3 or is a
String
. Examples are
List<Double>
,
Set<String>
, or
SortedSet<Integer>
.
Primitive type conversion
We've already seen a few examples of automatic string conversion into a primitive type.
Let's review a simple example again:
@GET
@Path
(
"{id}"
)
public
public
String
get
(
@PathParam
(
"id"
)
int
id
) {...}
Here, we're extracting an integer ID from a string-encoded segment of our incoming request
URI.
Java object conversion
Besides primitives, this string request data can be converted into a Java object before it is in-
jected into your JAX-RS method parameter. This object's class must have a constructor or a
static method named
valueOf()
that takes a single
String
parameter.
For instance, let's go back to the
@HeaderParam
example we used earlier in this chapter. In
that example, we used
@HeaderParam
to inject a string that represented the
Referer
header.
Since
Referer
is a URL, it would be much more interesting to inject it as an instance of
java.net.URL
: