Haxe Code Cookbook
Haxe programming cookbookBeginnerAccess a field by string

Access a field by string

Reading time: 1 minute

This snippet shows how to use a string as a variable identifier using reflection.

Implementation

class MyObject {
  @:keep var myField:String = "This is Reflection Test";
  
  public function new() { }
}

Usage

class Main {
  static public function main():Void {
    var myObject = new MyObject();
    
    var fieldName = "myField";
    var myField:String = Reflect.field(myObject, fieldName);
    trace(myField); // "This is Reflection Test";
  }
}

Haxe has dead code elimination (DCE). This compiler feature identifies and eliminates all unused code during compilation. In the example above, the variable myField is referenced only through reflection and not directly. Because of that, it will be marked for removal by DCE. To keep it from being eliminated, we need to add @:keep compiler metadata to the myField field. Note that @:keep could also be added to classes and functions. If you want to keep the class and its sub-classes, use @:keepSub.

Tip: Haxe has a wonderful type system, use this as much as possible. Reflection can be a powerful tool, but it's important to know it can be error prone, since the compiler can never validate if what you're doing makes sense and is also harder to optimize.

More information:


Contributors:
Mark Knol
flashultra
Last modified:
Created:
Category:  Beginner