Java Reference
In-Depth Information
ParamConverters
Sometimes a parameter class cannot use the default mechanisms to convert from string val-
ues. Either the class has no String constructor or no valueOf( ) method, or the ones that ex-
ist won't work with your HTTP requests. For this scenario, JAX-RS 2.0 has provided an ad-
ditional component to help with parameter conversions.
package
package javax . ws . rs . ext ;
public
public interface
interface ParamConverter
ParamConverter < T > {
public
public T fromString ( String value );
public
public String toString ( T value );
}
As you can see from the code, ParamConverter is a pretty simple interface. The
fromString() method takes a String and converts it to the desired Java type. The
toString() method does the opposite. Let's go back to our Color example. It pretty much
requires full uppercase for all Color parameters. Instead, let's write a ParamConverter that
allows a Color string to be any case.
public
public class
class ColorConverter
ColorConverter implements
implements ParamConverter < Color > {
public
public Color fromString ( String value ) {
iif ( value . equalsIgnoreCase ( BLACK . toString ())) return
return BLACK ;
else
else if ( value . equalsIgnoreCase ( BLUE . toString ())) return
return BLUE ;
else
else if ( value . equalsIgnoreCase ( RED . toString ())) return
return RED ;
else
else if ( value . equalsIgnoreCase ( WHITE . toString ())) return
return WHITE ;
else
else if ( value . equalsIgnoreCase ( SILVER . toString ())) return
return SILVER ;
throw
throw new
new IllegalArgumentException ( "Invalid color: " + value );
}
public
public String toString ( Color value ) { return
return value . toString (); }
}
We're still not done yet. We also have to implement the ParamConverterProvider inter-
face.
package
package javax . ws . rs . ext ;
public
public interface
interface ParamConverterProvider
ParamConverterProvider {
public
public < T > ParamConverter < T > getConverter ( Class < T > rawType ,
Type genericType ,
Annotation annotations []);
}
Search WWH ::




Custom Search