Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haxe Reference Object via String

Tags:

haxe

In Haxe, I am trying to access an object's value via a variable. In JavaScript you use [ ] to access it, but in Haxe this doesn't work and comes back with an error:

String should be Int

Array access is not allowed on { x : Int, name : String }

I need help with the last line of code:

var room = { x: 10, name: 'test' };

trace(room.name);   // this works returns 'test' 

// how do I reference foo to return 'test' as the above result.
var foo = "name";
var results = room[foo];   // need fixing
like image 950
Ferrari177 Avatar asked May 18 '26 00:05

Ferrari177


2 Answers

What you're trying to do is called Reflection, and the way to do that in Haxe is via the Reflect API:

var results = Reflect.field(room, "name");

If you want to access a static field instead, pass the Class<T> as the first argument instead of an instance:

class Foo {
    public static var bar = 0;
}

var bar = Reflect.field(Foo, "bar");

For properties with a getter, you'll want to use getProperty() instead.


Note: Reflection is generally considered bad practice as it moves errors from compile- to runtime and is inherently type-unsafe. There are usually better ways to solve a problem, but it's hard to recommend a concrete solution here without more context.

like image 176
Gama11 Avatar answered May 22 '26 17:05

Gama11


You could alternatively use haxe.DynamicAccess. This is particularly useful if your object is the result of haxe.Json.parse, or by other means a Dynamic.

However, since your example (indirectly) types room, some conversion is needed and you'll still loose typing (you'll have "values" with different types and will need to settle on <Dynamic>):

    var foo = "name";
    var access = (cast room:haxe.DynamicAccess<Dynamic>);
    trace(access[foo]);

(full example)

If your use case has a typed structure that can be converted into a String -> T map or if you're already dealing with dynamics, this is a good fit; otherwise, Reflect or untyped are simpler and therefore better.

like image 33
Jonas Malaco Avatar answered May 22 '26 15:05

Jonas Malaco