Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionScript - Determine If Value is Class Constant

i'd like to throw an argument error if a particular function doesn't work without a passed value that also happens to be a public constant of the class containing the function.

is there anyway to determine if a class owns a public constant instead of having to iterate thru all of them?

something like this:

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 functionality i have to write the city setter function like this:

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?

like image 415
Chunky Chunk Avatar asked Dec 14 '25 13:12

Chunky Chunk


2 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 to work, all constants must always be String objects declared public static const.

like image 123
weltraumpirat Avatar answered Dec 18 '25 08:12

weltraumpirat


I was looking for an answer to this question myself and found it annoying that hasOwnProperty() did not work for static properties. Turns out though, that if you cast your class to a Class object, it does work.

Here's an example:

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);
  }
}

I owe this solution to jimmy5804 from this discussion, so hats off to him.

like image 20
Atorian Avatar answered Dec 18 '25 09:12

Atorian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!