ActionScript - determining if a value is a class constant

I would like to cause an argument error if a particular function does not work without a passed value, which is also a public constant of the class containing this function.

one way or another, to determine whether a public constant belongs to the class instead of iterating through all of them?

something like that:

public static const HALIFAX:String = "halifax";
public static const MONTREAL:String = "montreal";
public static const TORONTO:String = "toronto";

private var cityProperty:String;

public function set city(value:String):void
     {
     if (!this.hasConstant(value))
        throw new ArgumentError("set city value is not applicable.");

     cityProperty = value;
     }

public function get city():Strig
     {
     return cityProperty;
     }

Currently, for this function, I have to write the city's set set function as follows:

public function set city(value:String):void
     {
     if (value != HALIFAX && value != MONTREAL && value != TORONTO)
        throw new ArgumentError("set city value is not applicable.");

     cityProperty = value;
     }

Is this the only way to accomplish this task?

+3
source share
3 answers

Yes, if you use reflections:

private var type:Class;
private var description:XML;

private function hasConstant (str : String ) : Boolean 
{
    if (description == null) 
    {
        type = getDefinitionByName (getQualifiedClassName (this)) as Class;
        description = describeType (type);      
    }
    for each ( var constant:XML in description.constant) 
    {
        if (type[constant.@name] == str) return true;
    }
    return false;
}

Note that for this, all constants must always be declared as String objects public static const.

+7

, , hasOwnProperty() . , , Class, .

:

public final class DisplayMode
{
  public static const one:   String = "one";
  public static const two:   String = "two";
  public static const three: String = "three";

  public static function isValid(aDisplayMode: String): Boolean {
    return Class(DisplayMode).hasOwnProperty(aDisplayMode);
  }
}

jimmy5804 , .

+3

. :

var foo:Sprite = new Sprite();
foo.rotation = 20;
trace( foo["x"], foo["rotation"]); // traces "0 20"

:

var bar:String = "rotation";
trace( foo[bar] ); // traces "20"

, , , ReferenceError, , , :

trace ( foo["cat"] ); // throws ReferenceError

, :

trace ( Sprite["cat"] ); // traces "undefined"

, :

if ( this[value] == undefined ) {
    throw new ArgumentError("set city value is not applicable.");
}

EDIT: , .

To do this, in order to work on your problem, you need to make the String value the same as the name const, for example:

public static const HALIFAX:String = "HALIFAX";

then you can use the query as described above and this will give you the desired result.

0
source

All Articles