I am new to Vala and playing around a bit. Currently I am looking for a way to determine the type parameter of a generic list at runtime.
The code below uses 'reflection' to print the properties of the Locations class. However, I am not able to determine at runtime that this list contains instances of string.
Is there a way to do this? Or is this not supported in Vala?
using Gee;
class Locations : Object {
public string numFound { get; set; }
public ArrayList<string> docs { get; set; }
}
void main () {
ObjectClass ocl = (ObjectClass) typeof (Locations).class_ref ();
ParamSpec[] properties = ocl.list_properties ();
foreach (ParamSpec spec in properties) {
string fieldName = spec.get_nick ();
stdout.printf (" fieldName: %s\n", fieldName);
Type fieldType = spec.value_type;
stdout.printf (" Type : %s\n", fieldType.name());
}
}
Output:
fieldName: numFound
Type : gchararray
fieldName: docs
Type : GeeArrayList
With the help of the suggestion of the first answer, I have come up with this solution. This is exactly what I was looking for:
Output:
There isn't a generic way to do this since GObject/GType simply isn't that expressive. For example, if you were using a
GLib.GenericArray
(or aGLib.List
) instead of aGee.ArrayList
you would be out of luck.That said, libgee does provide a way. Like most containers in libgee,
Gee.ArrayList
implementsGee.Traversable
, which includes theelement_type
property. Note, however, that you need an instance, not just theGLib.ObjectClass
.