Add TypeHandler.deserializeOrNull, deserializeOrGet, deserializeOrThrow
package org.terasology.persistence.typeHandling;
import java.util.Optional;
+import java.util.function.Supplier;
/**
* Serializes objects of type {@link T} to and from a {@link PersistedData}.
@@ -49,10 +50,50 @@ public PersistedData serialize(T value, PersistedDataSerializer serializer) {
}
/**
- * Deserializes a single value.
+ * Deserializes a single value to the type {@link T}.
*
- * @param data The persisted data to deserialize from
+ * @param data The persisted data to deserialize from.
* @return The deserialized value. {@link Optional#empty()} if the value could not be deserialized.
*/
public abstract Optional<T> deserialize(PersistedData data);
+
+ /**
+ * Deserializes a single value to the type {@link T}. If the type was not serialized
+ * (i.e. {@link #deserialize(PersistedData)} returned {@link Optional#empty()}), null is returned.
+ *
+ * @param data The persisted data to deserialize from.
+ * @return The deserialized value. {@code null} if the value could not be deserialized.
+ */
+ public final T deserializeOrNull(PersistedData data) {
+ return deserialize(data).orElse(null);
+ }
+
+ /**
+ * Deserializes a single value to the type {@link T}. If the type was not serialized
+ * (i.e. {@link #deserialize(PersistedData)} returned {@link Optional#empty()}), the value retrieved
+ * from the {@link Supplier} is returned.
+ *
+ * @param data The persisted data to deserialize from.
+ * @param supplier The {@link Supplier} from which to retrieve the value to be returned if
+ * {@code data} could not be deserialized.
+ * @return The deserialized value. If the value could not be deserialized, the value returned by
+ * {@code supplier.get()} is returned.
+ */
+ public final T deserializeOrGet(PersistedData data, Supplier<T> supplier) {
+ return deserialize(data).orElseGet(supplier);
+ }
+
+ /**
+ * Deserializes a single value to the type {@link T}. If the type was not serialized
+ * (i.e. {@link #deserialize(PersistedData)} returned {@link Optional#empty()}), a
+ * {@link DeserializationException} is thrown.
+ *
+ * @param data The persisted data to deserialize from.
+ * @return The deserialized value.
+ * @throws DeserializationException if {@code data} could not be deserialized to a value of type {@link T}.
+ */
+ public final T deserializeOrThrow(PersistedData data) throws DeserializationException {
+ return deserialize(data)
+ .orElseThrow(() -> new DeserializationException("Unable to deserialize " + data));
+ }
}
