1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
package testupgser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
*
* @author André Sébastien
*/
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try
{
// Création d'un classLoader pour charger l'ancienne version de Personne
URLClassLoader classLoaderV1 = new URLClassLoader( new URL[]{ new File("c:\\TestSer_v1.jar").toURI().toURL() } );
// Chargement de la classe Deserializer à partir du classLoader 'V1'
Class deserializerClass = classLoaderV1.loadClass("testser.Deserializer");
// Utilisation du Deserializer, on passe par un deserializer chargé par le classLoaderV1 afin que la méthode "latestUserDefinedLoader" de ObjectInputStream utilise notre classLoader V1
Object deserializer = deserializerClass.newInstance();
Object personneV1 = deserializerClass.getMethod("deserialize",String.class,File.class).invoke(deserializer,"testser.Personne", new File("c:\\personne_v1.ser") );
// Récuperation du Nom et du Prenom
String nom = (String)personneV1.getClass().getMethod("getNom",(Class[])null).invoke(personneV1,(Object[])null);
String prenom = (String)personneV1.getClass().getMethod("getPrenom",(Class[])null).invoke(personneV1,(Object[])null);
System.out.println("Nom = " + nom);
System.out.println("Prenom = " + prenom);
// Création d'une date de naissance arbitraire
Calendar naissance = new GregorianCalendar(1978,8,14);
// Création d'un objet Personne au format V2
URLClassLoader classLoaderV2 = new URLClassLoader( new URL[]{ new File("c:\\TestSer_v2.jar").toURI().toURL() } );
// Instanciation d'une personne V2
Class classPersonneV2 = classLoaderV2.loadClass("testser.Personne");
Object personneV2 = classPersonneV2.newInstance();
// Mise en place des données dans l'objet Personne V2
classPersonneV2.getMethod("setNom",String.class).invoke(personneV2,nom);
classPersonneV2.getMethod("setPrenom",String.class).invoke(personneV2,prenom);
classPersonneV2.getMethod("setDateNaissance",Calendar.class).invoke(personneV2,naissance);
// Sauvegarde
ObjectOutputStream oos = null;
try
{
oos = new ObjectOutputStream( new FileOutputStream( new File("c:\\personne_v2.ser") ) );
oos.writeObject(personneV2);
}
catch(Exception e2) { e2.printStackTrace(); }
finally
{
try
{
if( oos != null ) oos.close();
}
catch(Exception e2){ /* do nothing */ }
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
} |
Partager