Class Converter<A,B>
A to B with an associated reverse function from B
to 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 Doubles.stringConverter():
stringConverter().convert("1.00")returns theDoublevalue1.0stringConverter().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(A) method handles this null
behavior for all converters; implementations of doForward(A) and doBackward(B) 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(Class),Ints.stringConverteror the reverse views of these. - Convert between specific preset values using
Maps.asConverter. For example, use this to create a "fake" converter for a unit test. It is unnecessary (and confusing) to mock theConvertertype using a mocking framework. - Pass two lambda expressions or method references to the
fromfactory method. - Extend this class and implement its
doForward(A)anddoBackward(B)methods.
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)orconverter.reverse().convertAll(bs). - Use
converterorconverter.reverse()anywhere aFunctionis accepted (for exampleStream.map). - Do not call
doForward(A)ordoBackward(B)directly; these exist only to be overridden.
Example
return Converter.from(
Integer::toHexString,
s -> parseUnsignedInt(s, 16));
An alternative using a subclass:
return new Converter<Integer, String>() {
@Override
protected String doForward(Integer i) {
return Integer.toHexString(i);
}
@Override
protected Integer doBackward(String s) {
return parseUnsignedInt(s, 16);
}
}
- Since:
- 16.0
- Author:
- Mike Ward, Kurt Alfred Kluever, Gregory Kick
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionReturns a converter whoseconvertmethod appliessecondConverterto the result of this converter.final BDeprecated.Returns a representation ofaas an instance of typeB.convertAll(Iterable<? extends A> fromIterable) Returns an iterable that appliesconvertto each element offromIterable.protected abstract AdoBackward(B b) Returns a representation ofbas an instance of typeA.protected abstract BReturns a representation ofaas an instance of typeB.booleanMay returntrueifobjectis aConverterthat behaves identically to this converter.static <A,B> Converter <A, B> from(Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) Returns a converter based on separate forward and backward functions.static <T> Converter<T, T> identity()Returns a serializable converter that always converts or reverses an object to itself.reverse()Returns the reversed view of this converter, which convertsthis.convert(a)back to a value roughly equivalent toa.
-
Constructor Details
-
Converter
protected Converter()Constructor for use by subclasses.
-
-
Method Details
-
doForward
Returns a representation ofaas an instance of typeB. Ifacannot be converted, an unchecked exception (such asIllegalArgumentException) should be thrown.- Parameters:
a- the instance to convert; will never be null- Returns:
- the converted instance; must not be null
-
doBackward
Returns a representation ofbas an instance of typeA. Ifbcannot be converted, an unchecked exception (such asIllegalArgumentException) should be thrown.- Parameters:
b- the instance to convert; will never be null- Returns:
- the converted instance; must not be null
- Throws:
UnsupportedOperationException- if backward conversion is not implemented; this should be very rare. Note that if backward conversion is not only unimplemented but unimplementable (for example, consider aConverter<Chicken, ChickenNugget>), then this is not logically aConverterat all, and should just implementFunction.
-
convert
-
convertAll
Returns an iterable that appliesconvertto each element offromIterable. The conversion is done lazily.The returned iterable's iterator supports
remove()if the input iterator does. After a successfulremove()call,fromIterableno longer contains the corresponding element. -
reverse
Returns the reversed view of this converter, which convertsthis.convert(a)back to a value roughly equivalent toa.The returned converter is serializable if
thisconverter is.Note: you should not override this method. It is non-final for legacy reasons.
-
andThen
Returns a converter whoseconvertmethod appliessecondConverterto the result of this converter. Itsreversemethod applies the converters in reverse order.The returned converter is serializable if
thisconverter andsecondConverterare. -
apply
Deprecated.Provided to satisfy theFunctioninterface; useconvert(A)instead. -
equals
May returntrueifobjectis aConverterthat behaves identically to this converter.Warning: do not depend on the behavior of this method.
Historically,
Converterinstances in this library have implemented this method to recognize certain cases where distinctConverterinstances would in fact behave identically. However, this is not true ofConverterimplementations in general. It is best not to depend on it. -
from
public static <A,B> Converter<A,B> from(Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) Returns a converter based on separate forward and backward functions. This is useful if the function instances already exist, or so that you can supply lambda expressions. If those circumstances don't apply, you probably don't need to use this; subclassConverterand implement itsdoForward(A)anddoBackward(B)methods directly.These functions will never be passed
nulland must not under any circumstances returnnull. If a value cannot be converted, the function should throw an unchecked exception (typically, but not necessarily,IllegalArgumentException).The returned converter is serializable if both provided functions are.
- Since:
- 17.0
-
identity
Returns a serializable converter that always converts or reverses an object to itself.
-
Functioninterface; useconvert(A)instead.