View Javadoc

1   package org.apache.directmemory.serialization;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.ByteArrayOutputStream;
24  import java.io.IOException;
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  import java.io.ObjectStreamClass;
28  
29  public final class StandardSerializer
30      implements Serializer
31  {
32  
33      /**
34       * {@inheritDoc}
35       */
36      @Override
37      public <T> byte[] serialize( T obj )
38          throws IOException
39      {
40          ByteArrayOutputStream baos = new ByteArrayOutputStream();
41          ObjectOutputStream oos = new ObjectOutputStream( baos );
42          oos.writeObject( obj );
43          oos.flush();
44          oos.close();
45          return baos.toByteArray();
46      }
47  
48      /**
49       * {@inheritDoc}
50       */
51      @Override
52      public <T> T deserialize( byte[] source, final Class<T> clazz )
53          throws IOException, ClassNotFoundException
54      {
55          ByteArrayInputStream bis = new ByteArrayInputStream( source );
56          ObjectInputStream ois = new ObjectInputStream( bis )
57          {
58  
59              @Override
60              protected Class<?> resolveClass( ObjectStreamClass objectStreamClass )
61                  throws IOException, ClassNotFoundException
62              {
63                  ClassLoader classLoader = clazz.getClassLoader();
64                  return classLoader != null
65                      ? classLoader.loadClass( objectStreamClass.getName() )
66                      : Class.forName( objectStreamClass.getName() );
67              }
68  
69          };
70          T obj = clazz.cast( ois.readObject() );
71          ois.close();
72          return obj;
73      }
74  
75  }