Introspection - how?

Jacob Carlborg doob at me.com
Tue May 19 15:35:22 PDT 2009


Vincent wrote:
> Hello, guys!
> I have a question related D's introspection. I try to solve serialization task (implementing JSON protocol)
> and stuck at very start: getting all class' fields with types, names and values. Just test code:
> 
>     Thread d;
>     foreach(mi; d.classinfo.getMembers(null))
> 13:     writefln(mi.name);
> 
> test.d(13): Error: function object.MemberInfo.name () does not match parameter types ()
> test.d(13): Error: mi.name can only be called on a mutable object, not const(MemberInfo)
> 
> I'm confused with such strange error: what is a problem with using MemberInfo? I just try to GET info, not WRITE!
> Anybody have idea how to get info about members? (see task above)
> Thanks.

You can use tupleof for classes and structs which returns a tuple 
containing all the fields of the class/struct. The following code will 
print the type, name and value of every field in the struct. BTW you can 
change private fields with tupleof. This is tested dmd v1.043 and Tango.

struct Struct
{
	private int i = 3;
	private char c = 'a';
}

Struct s;

foreach (i, t ; typeof(Struct.tupleof))
{
	const len = Struct.stringof.length;
	const fieldName = Struct.tupleof[i].stringof[1 + len + 2 .. $];
	const typeName = typeof(Struct.tupleof[i]).stringof;
	
	Stdout.formatln("type: {0}", typeName);
	Stdout.formatln("name: {0}", fieldName);
	Stdout.formatln("value: {0}", s.tupleof[i]);
	Stdout().newline;
}

type: int
name: i
value: 3

type: char
name: c
value: a



More information about the Digitalmars-d mailing list