Re: [Ikvm-developers] Serialization of a java class
Brought to you by:
jfrijters
|
From: Jeroen F. <je...@su...> - 2006-08-28 11:20:21
|
Antoine Perridy wrote:
> Is it possible to get a java class serializable ?
> , so that the class will be define as [Serializable] in the=20
> code ? in java the class has to implements serializable...in=20
> the generated dll this class uses the interface :=20
> Serializable .__Interface
> Do you know how I can get this class to be [Serializable] ?
You can apply the SerializableAttribute like this:
@cli.System.SerializableAttribute.Annotation
public class MySerializableClass { .. }
But that alone won't get you a .NET serializable class (because
java.lang.Object currently isn't marked [Serializable]). So you need to
extend cli.System.Object or implement ISerializable.
Below are two examples.
Regards,
Jeroen
---- example 1 ----
import cli.System.IO.*;
import cli.System.Runtime.Serialization.*;
import cli.System.Runtime.Serialization.Formatters.Binary.*;
@cli.System.SerializableAttribute.Annotation
public class test extends cli.System.Object
{
private int i;
private transient int j;
public static void main(String[] args) throws Exception
{
MemoryStream mem =3D new MemoryStream();
BinaryFormatter formatter =3D new BinaryFormatter();
test obj =3D new test();
obj.i =3D 42;
obj.j =3D 123;
formatter.Serialize(mem, obj);
mem.Seek(0, SeekOrigin.wrap(SeekOrigin.Begin));
obj =3D (test)formatter.Deserialize(mem);
System.out.println(obj.i);
System.out.println(obj.j);
}
}
---- example 2 ----
import cli.System.IO.*;
import cli.System.Runtime.Serialization.*;
import cli.System.Runtime.Serialization.Formatters.Binary.*;
@cli.System.SerializableAttribute.Annotation
public class test implements ISerializable
{
private int i;
private transient int j;
public test()
{
}
public test(SerializationInfo info, StreamingContext context)
{
i =3D info.GetInt32("i");
}
public void GetObjectData(SerializationInfo info, StreamingContext
context)
{
info.AddValue("i", i); =20
}
public static void main(String[] args) throws Exception
{
MemoryStream mem =3D new MemoryStream();
BinaryFormatter formatter =3D new BinaryFormatter();
test obj =3D new test();
obj.i =3D 42;
obj.j =3D 123;
formatter.Serialize(mem, obj);
mem.Seek(0, SeekOrigin.wrap(SeekOrigin.Begin));
obj =3D (test)formatter.Deserialize(mem);
System.out.println(obj.i);
System.out.println(obj.j);
}
}
|