D RTTI?

Jacob Carlborg doob at me.com
Tue Mar 6 23:34:58 PST 2012


On 2012-03-06 19:17, H. S. Teoh wrote:
> On Tue, Mar 06, 2012 at 08:17:07AM +0100, Jacob Carlborg wrote:
>> On 2012-03-05 21:16, H. S. Teoh wrote:
>>> I know D doesn't really have RTTI yet, but I'm experimenting with
>>> "faking" it by doing something like:
>>>
>>> 	class A {
>>> 		string prop1;
>>> 		int prop2;
>>> 		...
>>> 		void serialize() {
>>> 			__serialize(this);
>>> 		}
>>> 	}
>>>
>>> 	void __serialize(T)(T obj) {
>>> 		writeln(typeid(obj));
>>> 		foreach (name; __traits(derivedMembers, T)) {
>>> 			writefln("%s = %s", name,
>>> 				__traits(getMember,obj,name));
>>> 		}
>>> 	}
> [...]
>> If you actually want serialization, and this was not just an
>> example, you can use Orange:
>>
>> https://github.com/jacob-carlborg/orange
>> http://www.dsource.org/projects/orange/
> [...]
>
> For my purposes, I will eventually need to serialize only a subset of an
> object's properties, and only for a certain class of objects. Does
> Orange support selective serializations?

Yes, but by default is serializes everything you give it. Orange 
supports several ways of customizing the serialization.

You can choose to not serialize specific fields or a whole class:

class Foo
{
     int a;
     int b;

     mixin NonSerialized!(b); // will not serialize "b"
}

class Foo
{
     int a;
     int b;

     mixin NonSerialized; // will not serialize "Foo" at all
}

If you want to customize the serialization process in even more detail 
that's possible as well, by implementing the Serializable interface:

class Foo : Serializable
{
     int a;

     void toData (Serializer serializer, Serializer.Data key)
     {
         serializer.serialize(a, "b");
     }

     void fromData (Serializer serializer, Serializer.Data key)
     {
         a = serializer.deserialize!(int)("b");
     }
}

Actually, you don't need to implement the interface, it will use compile 
time introspection to check if the methods are available. Or the 
unintrusive approach:

class Foo
{
     int a;
}

auto dg = (Foo value, Serializer serializer, Serializer.Data key) {
     serializer.serialize(a, "b");
}

Serializer.registerSerializer!(Foo)(dg);

You can find the docs here: 
http://dl.dropbox.com/u/18386187/orange_docs/orange.serialization.Serializer.html

In the docs, don't forget the "package" tab.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list