commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Gary Gregory <garydgreg...@gmail.com>
Subject [lang] SerializationUtils and generics
Date Thu, 05 Apr 2012 15:24:49 GMT
Hi All:

I'd like to propose the change below. This lets you get rid of type casts
in call sites. You'll still get a ClassCastException if you code it wrong
of course.

The compiler warning you'll get is valid, so do not think we should
@SuppressWarning against it.

Index: src/main/java/org/apache/commons/lang3/SerializationUtils.java
===================================================================
--- src/main/java/org/apache/commons/lang3/SerializationUtils.java
(revision 1302206)
+++ src/main/java/org/apache/commons/lang3/SerializationUtils.java
(working copy)
@@ -181,7 +181,7 @@
      * @throws IllegalArgumentException if {@code inputStream} is {@code
null}
      * @throws SerializationException (runtime) if the serialization fails
      */
-    public static Object deserialize(InputStream inputStream) {
+    public static <T> T deserialize(InputStream inputStream) {
         if (inputStream == null) {
             throw new IllegalArgumentException("The InputStream must not
be null");
         }
@@ -189,7 +189,7 @@
         try {
             // stream closed in the finally
             in = new ObjectInputStream(inputStream);
-            return in.readObject();
+            return (T) in.readObject();

         } catch (ClassNotFoundException ex) {
             throw new SerializationException(ex);
@@ -214,12 +214,11 @@
      * @throws IllegalArgumentException if {@code objectData} is {@code
null}
      * @throws SerializationException (runtime) if the serialization fails
      */
-    public static Object deserialize(byte[] objectData) {
+    public static <T> T deserialize(byte[] objectData) {
         if (objectData == null) {
             throw new IllegalArgumentException("The byte[] must not be
null");
         }
-        ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
-        return deserialize(bais);
+        return (T) deserialize(new ByteArrayInputStream(objectData));
     }

     /**

Gary
-- 
E-Mail: garydgregory@gmail.com | ggregory@apache.org
JUnit in Action, 2nd Ed: <http://goog_1249600977>http://bit.ly/ECvg0
Spring Batch in Action: <http://s.apache.org/HOq>http://bit.ly/bqpbCK
Blog: http://garygregory.wordpress.com
Home: http://garygregory.com/
Tweet! http://twitter.com/GaryGregory

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message