2017-02-11 1 views
3

개체 유형에 따라 논리를 포크하는 안전한 방법을 찾고 있습니다. 개체가 특정 제네릭 형식에 속하는지 확인하는 방법을 찾지 못했습니다.해당 개체가 Haxe에서 일반 인스턴스인지 확인하는 방법

class Test { 
    static function main() { 
     var aa = new AA<Int>(); 
     //ERROR: Cast type parameters must be Dynamic 
     //var a:A<Int> = cast(aa, A<Int>); 

     //ERROR: Unexpected) 
     //var a:A<Int> = Std.instance(aa, A<Int>); 

     //OK, but throw run-time exception with flash target. 
     var a:A<Int> = cast aa; 
     a.printName(); 

     //Run-time exception 
     a = cast "String is obviously wrong type"; 
    } 
} 

class A<T> { 
    public function new() { } 
    public function printName() { 
     trace("Generic name: A"); 
    } 
} 

class AA<T> extends A<T> { 
    public function new() { super(); } 
    override public function printName() { 
     trace("Generic name AA"); 
    } 
} 

개체가 제네릭 형식에 속하는지 여부를 확인할 수있는 합법적 인 방법이 있습니까?

+0

Flash에서 실행중인 런타임 예외를 재현 할 수 없습니다. 또한 코드 스 니펫에 'B'에 대한 유형 선언이 누락 된 것 같습니다. – Gama11

+0

SWF 타겟 및 디버그 플래시 플레이어로 http://try.haxe.org/#C6a93에서 확인할 수 있습니다. – kolonitsky

답변

4

정보를 런타임에 더 이상 사용할 수 없기 때문에 일반적으로이를 수행 할 수있는 방법이 없습니다.

class Main { 
    static function main() { 
     checkType(new A<Int>(5)); // Int 
     checkType(new A<Bool>(true)); // Bool 
     checkType(new A<B>(new B())); // B 
     checkType(new A<B>(null)); // unhandled type TNull 
    } 

    static function checkType<T>(a:A<T>) { 
     trace(switch (Type.typeof(a.value)) { 
      case TInt: "Int"; 
      case TBool: "Bool"; 
      case TClass(cls) if (cls == B): "B"; 
      case other: throw "unhandled type " + other; 
     }); 
    } 
} 

class A<T> { 
    public var value:T; 
    public function new (value:T) { 
     this.value = value; 
    } 
} 

class B { 
    public function new() {} 
} 
: A 유형 T의 필드가있는 경우이 같은 Type.typeOf()을 사용할 수 있습니다, 또는

class Main { 
    static function main() { 
     var a = new A<Int>(Int); 

     trace(a.typeParamIs(Int)); // true 
     trace(a.typeParamIs(Bool)); // false 
    } 
} 

class A<T> { 
    var type:Any; 

    public function new (type:Any) { 
     this.type = type; 
    } 

    public function typeParamIs(type:Any):Bool { 
     return this.type == type; 
    } 
} 

: 당신은 당신의 클래스에서 제네릭 형식을 저장하는 often suggested for Java입니다 같은 해결 방법을 사용할 수 있습니다

알 수 있듯이 보통 작동하는 동안 valuenull 일 때와 같이 예기치 않은 동작이 발생할 수 있습니다. 또한 Type.typeOf()의 문서를 염두에 두십시오.

플랫폼마다 다를 수 있습니다. 놀라움을 피하기 위해 이것에 관한 가정은 최소화되어야한다.


또한 판독이 다시 잠시 언급 한 mailing list thread. 매크로 솔루션은 여기에 언급되어 있습니다. 이 아닌 경우은 런타임에 유형을 알아야합니다.

관련 문제