AS3: Read-Only Property Detection

I have a simple AS3 class that just contains private variables. Each private variable has a getter function, but not all of them have setter functions. At run time, is there a way to tell which properties have no setters but are read-only? Then I can decide to provide the user with an input field for editing properties that have setters.

+3
source share
5 answers

Passing any object to a Type description will return you XML containing very detailed information about the object. know if your readonly can access the next node from xml,

xmlReturnedFromDescType.accessor.access

, - readonly, writeonly readwrite.

, .

+4

describeType try..catch

+2

, describeType(), XML, . , XML, API- AS3Commons-Reflect: http://www.as3commons.org

:

var type:Type = Type.forClass(MyClass);

for each (var accessor:Accessor in type.accessors) {
  if (accessor.writeable) {
    // do something with writeable property
  }
}
+1

, Type, DescribeTypeCache awesomeness ( )

+1

Type, .

: -

import flash.utils.describeType;

public static function hasSetter( subject : *, propName : String ) : Boolean
{
    var desc : XML = describeType( subject );
    var access : String = desc.accessor.(@name == propName).@access.toString();
    return ( access.indexOf( "write" ) > -1 );
}

public static function hasGetter( subject : *, propName : String ) : Boolean
{
    var desc : XML = describeType( subject );
    var access : String = desc.accessor.(@name == propName).@access.toString();
    return ( access.indexOf( "read" ) > -1 );
}

and tousdan point - if you are going to do this, then create a cache. I don't like to include mx libraries unless I need me to prepare this simple caching:

public static function getTypeDescription( instance : * ) : XML
{
    var key : String = getSimpleClassName( instance );

    switch( true )
    {
        case ( typeDescriptions == null ) :
            typeDescriptions = new Object();
            typeDescriptions[ key ] = describeType( instance );
            break;
        case ( typeDescriptions[ key ] == null ) :
            typeDescriptions[ key ] = describeType( instance );
            break;
        case ( typeDescriptions[ key ] != null ) :
            // do nothing
            break;
        default :
            trace( "\tERROR : unhanded case DataUtils.getTypeDescription." );
            return null;
            break;
    }

    return typeDescriptions[ key ] as XML;
}

public static function getSimpleClassName( instance : * ) : String
{
    var className : String = String( getClass( instance ) );
    className = className.substring( 7, className.length - 1 );
    return( className );
}
0
source

Source: https://habr.com/ru/post/1761807/


All Articles