From 1da24e8c3b89f7a46f02f75cff2011cf504cfd66 Mon Sep 17 00:00:00 2001 From: lukaseder Date: Wed, 6 Jul 2016 14:19:40 +0200 Subject: [PATCH] [#5398] Add also Converter.ofNullable() --- jOOQ/src/main/java/org/jooq/Converter.java | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/jOOQ/src/main/java/org/jooq/Converter.java b/jOOQ/src/main/java/org/jooq/Converter.java index 394743ca29..95cc373a99 100644 --- a/jOOQ/src/main/java/org/jooq/Converter.java +++ b/jOOQ/src/main/java/org/jooq/Converter.java @@ -172,5 +172,47 @@ public interface Converter extends Serializable { }; } + /** + * Construct a new converter from functions. + *

+ * This works like {@link Converter#of(Class, Class, Function, Function)}, + * except that both conversion {@link Function}s are decorated with a + * function that always returns null for null + * inputs. + *

+ * Example: + *

+ *

+     * Converter converter =
+     *   Converter.ofNullable(String.class, Integer.class, Integer::parseInt, Object::toString);
+     *
+     * // No exceptions thrown
+     * assertNull(converter.from(null));
+     * assertNull(converter.to(null));
+     * 
+ * + * @param the database type + * @param the user type + * @param fromType The database type + * @param toType The user type + * @param from A function converting from T to U + * @param to A function converting from U to T + * @return The converter. + * @see Converter + */ + static Converter ofNullable( + Class fromType, + Class toType, + Function from, + Function to + ) { + return of( + fromType, + toType, + t -> t == null ? null : from.apply(t), + u -> u == null ? null : to.apply(u) + ); + } + }