Search code examples
linuxclassubuntugtkvala

Vala: Pass String as Class


Scenario: I have x number of classes. Lets say 10; Each class does different UI Functions. When a user loads a file, that extension tells the program the classname to load; but it's in the form of a string.

Is there anyway to pass a string off as a classname? Something to the effect of.

 var classname = "Booger";

 var nose = new classname(){ //classname really means "Booger"
 //Do Operation
 }

Solution

  • You can reflect a type by name using var t = Type.from_name(classname);, however, this works on all types, including enums and structs and it might be the type Type.INVALID. You should probably do some checks, like t.is_a(typeof(MyParentClass)).

    You can then instantiate a copy using var obj = Object.new(t);. The whole thing would look like:

    var classname = "Booger";
    var t = Type.from_name(classname);
    if (t.is_a(typeof(MyParentClass)))
      return Object.new(t);
    else
      return null;
    

    It's also worth noting that the run-time type names have the namespace prepended, so you might want to do "MyNs" + classname. You can check in either the generated C or doing typeof(MyClass).name().