source: src/main/java/weka/core/SerializationHelper.java @ 19

Last change on this file since 19 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 9.7 KB
Line 
1/*
2 *    This program is free software; you can redistribute it and/or modify
3 *    it under the terms of the GNU General Public License as published by
4 *    the Free Software Foundation; either version 2 of the License, or
5 *    (at your option) any later version.
6 *
7 *    This program is distributed in the hope that it will be useful,
8 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *    GNU General Public License for more details.
11 *
12 *    You should have received a copy of the GNU General Public License
13 *    along with this program; if not, write to the Free Software
14 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17/*
18 * SerializationHelper.java
19 * Copyright (C) 2007 University of Waikato, Hamilton, New Zealand
20 */
21
22package weka.core;
23
24import java.io.FileInputStream;
25import java.io.FileOutputStream;
26import java.io.InputStream;
27import java.io.ObjectInputStream;
28import java.io.ObjectOutputStream;
29import java.io.ObjectStreamClass;
30import java.io.OutputStream;
31import java.io.Serializable;
32import java.util.Vector;
33
34/**
35 * A helper class for determining serialVersionUIDs and checking whether
36 * classes contain one and/or need one. One can also serialize and deserialize
37 * objects to and fro files or streams.
38 *
39 * @author  fracpete (fracpete at waikato dot ac dot nz)
40 * @version $Revision: 5953 $
41 */
42public class SerializationHelper
43  implements RevisionHandler {
44
45  /** the field name of serialVersionUID. */
46  public final static String SERIAL_VERSION_UID = "serialVersionUID";
47 
48  /**
49   * checks whether a class is serializable.
50   *
51   * @param classname   the class to check
52   * @return            true if the class or one of its ancestors implements
53   *                    the Serializable interface, otherwise false (also if
54   *                    the class cannot be loaded)
55   */
56  public static boolean isSerializable(String classname) {
57    boolean     result;
58   
59    try {
60      result = isSerializable(Class.forName(classname));
61    }
62    catch (Exception e) {
63      result = false;
64    }
65     
66    return result;
67  }
68 
69  /**
70   * checks whether a class is serializable.
71   *
72   * @param c           the class to check
73   * @return            true if the class or one of its ancestors implements
74   *                    the Serializable interface, otherwise false
75   */
76  public static boolean isSerializable(Class c) {
77    return ClassDiscovery.hasInterface(Serializable.class, c);
78  }
79 
80  /**
81   * checks whether the given class contains a serialVersionUID.
82   *
83   * @param classname   the class to check
84   * @return            true if the class contains a serialVersionUID,
85   *                    otherwise false (also if the class is not
86   *                    implementing serializable or cannot be loaded)
87   */
88  public static boolean hasUID(String classname) {
89    boolean     result;
90   
91    try {
92      result = hasUID(Class.forName(classname));
93    }
94    catch (Exception e) {
95      result = false;
96    }
97   
98    return result;
99  }
100
101  /**
102   * checks whether the given class contains a serialVersionUID.
103   *
104   * @param c           the class to check
105   * @return            true if the class contains a serialVersionUID,
106   *                    otherwise false (also if the class is not
107   *                    implementing serializable)
108   */
109  public static boolean hasUID(Class c) {
110    boolean     result;
111   
112    result = false;
113   
114    if (isSerializable(c)) {
115      try {
116        c.getDeclaredField(SERIAL_VERSION_UID);
117        result = true;
118      }
119      catch (Exception e) {
120        result = false;
121      }
122    }
123   
124    return result;
125  }
126 
127  /**
128   * checks whether a class needs to declare a serialVersionUID, i.e., it
129   * implements the java.io.Serializable interface but doesn't declare a
130   * serialVersionUID.
131   *
132   * @param classname   the class to check
133   * @return            true if the class needs to declare one, false otherwise
134   *                    (also if the class cannot be loaded!)
135   */
136  public static boolean needsUID(String classname) {
137    boolean     result;
138   
139    try {
140      result = needsUID(Class.forName(classname));
141    }
142    catch (Exception e) {
143      result = false;
144    }
145   
146    return result;
147  }
148 
149  /**
150   * checks whether a class needs to declare a serialVersionUID, i.e., it
151   * implements the java.io.Serializable interface but doesn't declare a
152   * serialVersionUID.
153   *
154   * @param c           the class to check
155   * @return            true if the class needs to declare one, false otherwise
156   */
157  public static boolean needsUID(Class c) {
158    boolean     result;
159   
160    if (isSerializable(c))
161      result = !hasUID(c);
162    else
163      result = false;
164   
165    return result;
166  }
167 
168  /**
169   * reads or creates the serialVersionUID for the given class.
170   *
171   * @param classname   the class to get the serialVersionUID for
172   * @return            the UID, 0L for non-serializable classes (or if the
173   *                    class cannot be loaded)
174   */
175  public static long getUID(String classname) {
176    long        result;
177   
178    try {
179      result = getUID(Class.forName(classname));
180    }
181    catch (Exception e) {
182      result = 0L;
183    }
184   
185    return result;
186  }
187 
188  /**
189   * reads or creates the serialVersionUID for the given class.
190   *
191   * @param c           the class to get the serialVersionUID for
192   * @return            the UID, 0L for non-serializable classes
193   */
194  public static long getUID(Class c) {
195    return ObjectStreamClass.lookup(c).getSerialVersionUID();
196  }
197
198  /**
199   * serializes the given object to the specified file.
200   *
201   * @param filename    the file to write the object to
202   * @param o           the object to serialize
203   * @throws Exception  if serialization fails
204   */
205  public static void write(String filename, Object o) throws Exception {
206    write(new FileOutputStream(filename), o);
207  }
208
209  /**
210   * serializes the given object to the specified stream.
211   *
212   * @param stream      the stream to write the object to
213   * @param o           the object to serialize
214   * @throws Exception  if serialization fails
215   */
216  public static void write(OutputStream stream, Object o) throws Exception {
217    ObjectOutputStream  oos;
218   
219    oos = new ObjectOutputStream(stream);
220    oos.writeObject(o);
221    oos.flush();
222    oos.close();
223  }
224
225  /**
226   * serializes the given objects to the specified file.
227   *
228   * @param filename    the file to write the object to
229   * @param o           the objects to serialize
230   * @throws Exception  if serialization fails
231   */
232  public static void writeAll(String filename, Object[] o) throws Exception {
233    writeAll(new FileOutputStream(filename), o);
234  }
235
236  /**
237   * serializes the given objects to the specified stream.
238   *
239   * @param stream      the stream to write the object to
240   * @param o           the objects to serialize
241   * @throws Exception  if serialization fails
242   */
243  public static void writeAll(OutputStream stream, Object[] o) throws Exception {
244    ObjectOutputStream  oos;
245    int                 i;
246   
247    oos = new ObjectOutputStream(stream);
248    for (i = 0; i < o.length; i++)
249      oos.writeObject(o[i]);
250    oos.flush();
251    oos.close();
252  }
253
254  /**
255   * deserializes the given file and returns the object from it.
256   *
257   * @param filename    the file to deserialize from
258   * @return            the deserialized object
259   * @throws Exception  if deserialization fails
260   */
261  public static Object read(String filename) throws Exception {
262    return read(new FileInputStream(filename));
263  }
264
265  /**
266   * deserializes from the given stream and returns the object from it.
267   *
268   * @param stream      the stream to deserialize from
269   * @return            the deserialized object
270   * @throws Exception  if deserialization fails
271   */
272  public static Object read(InputStream stream) throws Exception {
273    ObjectInputStream   ois;
274    Object              result;
275   
276    ois = new ObjectInputStream(stream);
277    result = ois.readObject();
278    ois.close();
279   
280    return result;
281  }
282
283  /**
284   * deserializes the given file and returns the objects from it.
285   *
286   * @param filename    the file to deserialize from
287   * @return            the deserialized objects
288   * @throws Exception  if deserialization fails
289   */
290  public static Object[] readAll(String filename) throws Exception {
291    return readAll(new FileInputStream(filename));
292  }
293
294  /**
295   * deserializes from the given stream and returns the object from it.
296   *
297   * @param stream      the stream to deserialize from
298   * @return            the deserialized object
299   * @throws Exception  if deserialization fails
300   */
301  public static Object[] readAll(InputStream stream) throws Exception {
302    ObjectInputStream   ois;
303    Vector<Object>              result;
304   
305    ois    = new ObjectInputStream(stream);
306    result = new Vector<Object>();
307    try {
308      while (true) {
309        result.add(ois.readObject());
310      }
311    }
312    catch (Exception e) {
313      // ignored
314    }
315    ois.close();
316   
317    return result.toArray(new Object[result.size()]);
318  }
319 
320  /**
321   * Returns the revision string.
322   *
323   * @return            the revision
324   */
325  public String getRevision() {
326    return RevisionUtils.extract("$Revision: 5953 $");
327  }
328 
329  /**
330   * Outputs information about a class on the commandline, takes class
331   * name as arguments.
332   *
333   * @param args        the classnames to check
334   * @throws Exception  if something goes wrong
335   */
336  public static void main(String[] args) throws Exception {
337    if (args.length == 0) {
338      System.out.println("\nUsage: " + SerializationHelper.class.getName() + " classname [classname [classname [...]]]\n");
339      System.exit(1);
340    }
341   
342    // check all the classes
343    System.out.println();
344    for (int i = 0; i < args.length; i++) {
345      System.out.println(args[i]);
346      System.out.println("- is serializable: " + isSerializable(args[i]));
347      System.out.println("- has " + SERIAL_VERSION_UID + ": " + hasUID(args[i]));
348      System.out.println("- needs " + SERIAL_VERSION_UID + ": " + needsUID(args[i]));
349      System.out.println("- " + SERIAL_VERSION_UID + ": private static final long serialVersionUID = " + getUID(args[i]) + "L;");
350      System.out.println();
351    }
352  }
353}
Note: See TracBrowser for help on using the repository browser.