Re: [Vala] Reflection : getting values in Gee.Collection



​Baptize Gelez,

Here is an example how I'd do it:

File 'vala_test.vala':

using Gee;

interface ISerializable : Object {
    public abstract string[] serializable_keys();
    public abstract string[] serializable_values();
}

class SerializableClass : ISerializable, Object {

    string prop1;
    ArrayList<string> prop2;

    public SerializableClass (){
        prop1 = "bla!";
        prop2 = new ArrayList<string>();
        prop2.add ("100");
        prop2.add ("10");
        prop2.add ("1");
    }

    public string[] serializable_keys () {
        var result = new GLib.Array<string>();
        result.append_val ("prop1");

        for (int i = 0; i < prop2.size; i++)
            result.append_val (@"prop2[$i]");

        return result.data;
    }

    public string[] serializable_values () {
        var result = new GLib.Array<string>();
        result.append_val (@"$prop1");

        for (int i = 0; i < prop2.size; i++)
            result.append_val (@"$(prop2[i])");

        return result.data;
    }
}

HashMap<string,string> create_model(ISerializable serializable) {
    var result = new HashMap<string, string>();
    var keys = serializable.serializable_keys();
    var values = serializable.serializable_values();

    for (int i = 0; i < keys.length; i++)
        result  set(keys[i], values[i]);

    return result;
}


class Main {

    static void main() {
        var object_under_test = new SerializableClass();
        var model = create_model(object_under_test);

        var it = model.iterator ();
        for (var has_next = it.next (); has_next; has_next = it.next ()) {
            var key = it.get().key;
            var value = it.get().value;
            stdout.printf(@"$key -> $value\n");
        }
    }
}

$ valac vala_test.vala --pkg gee-0.8
$ ./vala_test
prop2[1] -> 10
prop2[0] -> 100
prop2[2] -> 1
prop1 -> bla!

​


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]