A function from
A to
B with an associated
reverse function from
Bto
A; used for converting back and forth between
different representations of the same
information.
Invertibility
The reverse operation may be a strict inverse (meaning that
converter.reverse().convert(converter.convert(a)).equals(a) is always true). However, it is
very common (perhaps more common) for round-trip conversion to be lossy. Consider
an example round-trip using
jersey.repackaged.com.google.common.primitives.Doubles#stringConverter:
-
stringConverter().convert("1.00") returns the
Double value
1.0
-
stringConverter().reverse().convert(1.0) returns the string
"1.0" --
not the same string (
"1.00") we started with
Note that it should still be the case that the round-tripped and original objects are
similar.
Nullability
A converter always converts
null to
null and non-null references to non-null
references. It would not make sense to consider
null and a non-null reference to be
"different representations of the same information", since one is distinguishable from
missing information and the other is not. The
#convert method handles this null
behavior for all converters; implementations of
#doForward and
#doBackward are
guaranteed to never be passed
null, and must never return
null.
Common ways to use
Getting a converter:
- Use a provided converter implementation, such as
Enums#stringConverter,
jersey.repackaged.com.google.common.primitives.Ints#stringConverter or the
#reverse views of these.
- Convert between specific preset values using
jersey.repackaged.com.google.common.collect.Maps#asConverter. For example, use this to create
a "fake" converter for a unit test. It is unnecessary (and confusing) to mock the
Converter type using a mocking framework.
- Otherwise, extend this class and implement its
#doForward and
#doBackwardmethods.
Using a converter:
- Convert one instance in the "forward" direction using
converter.convert(a).
- Convert multiple instances "forward" using
converter.convertAll(as).
- Convert in the "backward" direction using
converter.reverse().convert(b) or
converter.reverse().convertAll(bs).
- Use
converter or
converter.reverse() anywhere a
Function is accepted
- Do not call
#doForward or
#doBackward directly; these exist only to be
overridden.