Browse Source

added Type.createEnum

Nicolas Cannasse 17 years ago
parent
commit
2a26ba9bd8
4 changed files with 37 additions and 0 deletions
  1. 1 0
      doc/CHANGES.txt
  2. 15 0
      std/Type.hx
  3. 1 0
      tests/unit/MyClass.hx
  4. 20 0
      tests/unit/TestReflect.hx

+ 1 - 0
doc/CHANGES.txt

@@ -49,6 +49,7 @@ TODO inlining : substitute class+function type parameters in order to have fully
 	added parameters default value (constants)
 	added parameters default value (constants)
 	removed Std.resource, Std.ord, Std.chr
 	removed Std.resource, Std.ord, Std.chr
 	added haxe.Resource, allow binary data in resources
 	added haxe.Resource, allow binary data in resources
+	added Type.createEnum
 
 
 2008-04-05: 1.19
 2008-04-05: 1.19
 	fixed flash9 Array.toString
 	fixed flash9 Array.toString

+ 15 - 0
std/Type.hx

@@ -290,6 +290,21 @@ class Type {
 		#end
 		#end
 	}
 	}
 
 
+	/**
+		Create an instance of an enum by using a constructor name and parameters.
+	**/
+	public static function createEnum( e : Enum, constr : String, ?params : Array<Dynamic> ) : Dynamic {
+		var f = Reflect.field(e,constr);
+		if( f == null ) throw "No such constructor "+constr;
+		if( Reflect.isFunction(f) ) {
+			if( params == null ) throw "Constructor "+constr+" need parameters";
+			return Reflect.callMethod(e,f,params);
+		}
+		if( params != null && params.length != 0 )
+			throw "Constructor "+constr+" does not need parameters";
+		return f;
+	}
+
 	#if flash9
 	#if flash9
 	static function describe( t : Dynamic, fact : Bool ) untyped {
 	static function describe( t : Dynamic, fact : Bool ) untyped {
 		var fields = new Array();
 		var fields = new Array();

+ 1 - 0
tests/unit/MyClass.hx

@@ -10,6 +10,7 @@ class MyClass {
 
 
 	public function new(v) {
 	public function new(v) {
 		val = v;
 		val = v;
+		intValue = 55;
 	}
 	}
 
 
 	public function get() {
 	public function get() {

+ 20 - 0
tests/unit/TestReflect.hx

@@ -153,4 +153,24 @@ class TestReflect extends Test {
 		eq( Std.parseInt("0xFF"), 255 );
 		eq( Std.parseInt("0xFF"), 255 );
 	}
 	}
 
 
+	function testCreate() {
+		var i = Type.createInstance(MyClass,[33]);
+		t( Std.is(i,MyClass) );
+		eq( i.get(), 33 );
+		eq( i.intValue, 55 );
+		var i = Type.createEmptyInstance(MyClass);
+		t( Std.is(i,MyClass) );
+		eq( i.get(), #if flash9 0 #else null #end );
+		eq( i.intValue, #if flash9 0 #else null #end );
+		var e : MyEnum = Type.createEnum(MyEnum,"A");
+		eq( e, MyEnum.A );
+		var e : MyEnum = Type.createEnum(MyEnum,"C",[55,"hello"]);
+		switch( e ) {
+		case C(i,s): eq(i,55); eq(s,"hello");
+		default: assert();
+		}
+		exc( function() Type.createEnum(MyEnum,"A",[0]) );
+		exc( function() Type.createEnum(MyEnum,"C") );
+	}
+
 }
 }