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



Another form is to subclass ArrayList<string>, the resulting class can be
instantiated used simple Object.new() using your subclass' type. Then you
can call any method available for Gee.ArrayList or Gee.Collection by
casting to the object you need.

But defining a Serializable interface is good. In GXml, we need to
initialize all your Gee collections properties on creation, in order to
access them at run time, is not possible to create a Gee generic class at
runtime, if you want to do so in a generic, no hard coded, way.
El abr. 10, 2016 5:21 PM, "Felipe Lavratti" <felipelav gmail com> escribió:

​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!

​
_______________________________________________
vala-list mailing list
vala-list gnome org
https://mail.gnome.org/mailman/listinfo/vala-list



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