Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
 }
like image 888
Chris Timberlake Avatar asked Dec 08 '25 21:12

Chris Timberlake


1 Answers

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().

like image 140
apmasell Avatar answered Dec 10 '25 12:12

apmasell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!