Class Converter<A,B>
- java.lang.Object
-
- com.google.common.base.Converter<A,B>
-
- All Implemented Interfaces:
Function<A,B>
@Beta @GwtCompatible public abstract class Converter<A,B> extends java.lang.Object implements Function<A,B>
A function fromAtoBwith an associated reverse function fromBtoA; 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 usingDoubles.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
nulltonulland non-null references to non-null references. It would not make sense to considernulland a non-null reference to be "different representations of the same information", since one is distinguishable from missing information and the other is not. Theconvert(A)method handles this null behavior for all converters; implementations ofdoForward(A)anddoBackward(B)are guaranteed to never be passednull, and must never returnnull.Common ways to use
Getting a converter:
- Use a provided converter implementation, such as
Enums.stringConverter(java.lang.Class<T>),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. - Otherwise, 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 - Do not call
doForward(A)ordoBackward(B)directly; these exist only to be overridden.
- Since:
- 16.0
-
-
Constructor Summary
Constructors Modifier Constructor Description protectedConverter()Constructor for use by subclasses.
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Concrete Methods Deprecated Methods Modifier and Type Method Description <C> Converter<A,C>andThen(Converter<B,C> secondConverter)Returns a converter whoseconvertmethod appliessecondConverterto the result of this converter.Bapply(A a)Deprecated.Provided to satisfy theFunctioninterface; useconvert(A)instead.Bconvert(A a)Returns a representation ofaas an instance of typeB.java.lang.Iterable<B>convertAll(java.lang.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 BdoForward(A a)Returns a representation ofaas an instance of typeB.booleanequals(java.lang.Object object)Indicates whether another object is equal 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 existing forward and backward functions.static <T> Converter<T,T>identity()Returns a serializable converter that always converts or reverses an object to itself.Converter<B,A>reverse()Returns the reversed view of this converter, which convertsthis.convert(a)back to a value roughly equivalent toa.
-
-
-
Method Detail
-
doForward
protected abstract B doForward(A a)
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
protected abstract A doBackward(B b)
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:
java.lang.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
@Nullable public final B convert(@Nullable A a)
Returns a representation ofaas an instance of typeB.- Returns:
- the converted value; is null if and only if
ais null
-
convertAll
public java.lang.Iterable<B> convertAll(java.lang.Iterable<? extends A> fromIterable)
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
public Converter<B,A> 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.
-
andThen
public <C> Converter<A,C> andThen(Converter<B,C> secondConverter)
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 @Nullable public final B apply(@Nullable A a)
Deprecated.Provided to satisfy theFunctioninterface; useconvert(A)instead.Description copied from interface:FunctionReturns the result of applying this function toinput. This method is generally expected, but not absolutely required, to have the following properties:- Its execution does not cause any observable side effects.
- The computation is consistent with equals; that is,
Objects.equal(a, b)implies thatObjects.equal(function.apply(a), function.apply(b)).
-
equals
public boolean equals(@Nullable java.lang.Object object)
Indicates whether another object is equal to this converter.Most implementations will have no reason to override the behavior of
Object.equals(java.lang.Object). However, an implementation may also choose to returntruewheneverobjectis aConverterthat it considers interchangeable with this one. "Interchangeable" typically means thatObjects.equal(this.convert(a), that.convert(a))is true for allaof typeA(and similarly forreverse). Note that afalseresult from this method does not imply that the converters are known not to be interchangeable.
-
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 existing forward and backward functions. Note that it is unnecessary to create new classes implementingFunctionjust to pass them in here. Instead, simply 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
public static <T> Converter<T,T> identity()
Returns a serializable converter that always converts or reverses an object to itself.
-
-