Accueil > Java > Serialisation Test de bon fonctionnement

Serialisation Test de bon fonctionnement

28/01/2009
  1. import java.io.ByteArrayInputStream;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.ObjectInputStream;  
  6. import java.io.ObjectOutputStream;  
  7.   
  8. public class TestMain {  
  9.   
  10.     public static void main(String[] args) {  
  11.         // construct test object  
  12.         ObjectA originalObj = new ObjectA();  
  13.   
  14.         testSerialization(originalObj);  
  15.   
  16.     }  
  17.   
  18.     public static void testSerialization (Object originalObj)  
  19.     {  
  20.         ObjectA extractedObj = null;  
  21.   
  22.         // serialize  
  23.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  24.         ObjectOutputStream oos;  
  25.   
  26.         System.out.println("Trying to serialize the object...");  
  27.         try {  
  28.             oos = new ObjectOutputStream(out);  
  29.             oos.writeObject(originalObj);  
  30.             oos.close();  
  31.             System.out.println("=>> Success.");  
  32.         } catch (IOException e) {  
  33.             System.err.println("=>> Failure: "+e.getMessage());  
  34.             e.printStackTrace();  
  35.             return;  
  36.         }  
  37.   
  38.         //deserialize  
  39.         byte[] pickled = out.toByteArray();  
  40.         InputStream in = new ByteArrayInputStream(pickled);  
  41.         ObjectInputStream ois;  
  42.   
  43.         System.out.println("Trying to deserialize the object...");  
  44.         try {  
  45.             ois = new ObjectInputStream(in);  
  46.             Object obj = ois.readObject();  
  47.             extractedObj = (ObjectA) obj;  
  48.             System.out.println("=>> Success.");  
  49.         } catch (IOException e) {  
  50.             System.err.println("=>> Failure: "+e.getMessage());  
  51.             return;  
  52.         } catch (ClassNotFoundException e) {  
  53.             System.err.println("=>> Failure: "+e.getMessage());  
  54.             e.printStackTrace();  
  55.             return;  
  56.         }  
  57.   
  58.         // test the result  
  59.         System.out.println("Inuring that the extracted object is equal to the original one...");  
  60.         if (!originalObj.equals(extractedObj)) {  
  61.             System.err.println("=>> Failure: Objects are not equals.");  
  62.             return;  
  63.         } else {  
  64.             System.out.println("=>> Success.");  
  65.         }  
  66.       }  
  67. }  

Java

Les commentaires sont fermés.