A function from 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
| 108 | |
| 109 | |
| 110 | @Beta |
| 111 | @GwtCompatible |
| 112 | public abstract class Converter<A, B> implements Function<A, B> { |
| 113 | private final boolean handleNullAutomatically; |
| 114 | |
| 115 | // We lazily cache the reverse view to avoid allocating on every call to reverse(). |
| 116 | |
| 117 | private transient Converter<B, A> reverse; |
| 118 | |
| 119 | /** Constructor for use by subclasses. */ |
| 120 | |
| 121 | |
| 122 | protected Converter() { |
| 123 | this(true); |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. |
| 128 | */ |
| 129 | |
| 130 | Converter(boolean handleNullAutomatically) { |
| 131 | this.handleNullAutomatically = handleNullAutomatically; |
| 132 | } |
| 133 | |
| 134 | // SPI methods (what subclasses must implement) |
| 135 | |
| 136 | /** |
| 137 | * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be |
| 138 | * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. |
| 139 | * |
| 140 | * @param a the instance to convert; will never be null |
| 141 | * @return the converted instance; <b>must not</b> be null |
| 142 | */ |
| 143 | |
| 144 | |
| 145 | protected abstract B doForward(A a); |
| 146 | |
| 147 | /** |
| 148 | * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be |
| 149 | * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. |
| 150 | * |
| 151 | * @param b the instance to convert; will never be null |
| 152 | * @return the converted instance; <b>must not</b> be null |
| 153 | * @throws UnsupportedOperationException if backward conversion is not implemented; this should be |
| 154 | * very rare. Note that if backward conversion is not only unimplemented but |
| 155 | * unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}), |
| 156 | * then this is not logically a {@code Converter} at all, and should just implement {@link |
| 157 | * Function}. |
| 158 | */ |
| 159 | |
| 160 | |
| 161 | protected abstract A doBackward(B b); |
| 162 | |
| 163 | // API (consumer-side) methods |
| 164 | |
| 165 | /** |
| 166 | * Returns a representation of {@code a} as an instance of type {@code B}. |
| 167 | * |
nothing calls this directly
no outgoing calls
no test coverage detected