How can I make use of the static field names returned by getClassFields()
?
Type
itself doesn't seem to have any functions related to this, and if you use Reflect
like this on a field name returned by the above:
trace(Reflect.field(Type.createEmptyInstance(Type.resolveClass(...)), fieldName));
...you get:
TypeError: Error #1010: A term is undefined and has no properties.
My goal is to obtain the value of a static field using a classname given dynamically, e.g. how can I get "hi"
out of:
class Blah {
public static var test:String="hi";
}
...when I don't know Blah in advance?
Running Haxe 3.2.1.
This should work:
var cl = Type.resolveClass("Blah");
trace(Reflect.field(cl, "test"));
Static fields need to be accessed through a Class<T>
type, so createEmptyInstance()
doesn't work here. You need to pass an instance to Reflect.field()
if you want to retrieve the value of an instance field.
You also need to make sure that Blah
is actually compiled and available at runtime. If it is only referenced via reflection, this won't be the case - it needs to be imported somewhere. If you have DCE enabled, the class additionally needs @:keep
metadata.