I have a simple AS3 class that just holds private variables. Each private variable has a getter function, but not all of them have setter functions. At run开发者_运维知识库time, Is there a way of telling which properties do not have setters but are read-only? Then I can decide to give the user an input field to edit the properties that have setters.
Passing any object to describeType would return you XML containing very detailed information about object. to know if its readonly you can access following node of xml,
xmlReturnedFromDescType.accessor.access
This would be one of three, namely - readonly, writeonly, and readwrite.
Hope this helps.
i'd suggest describeType or try..catch
As mentioned, you can use describeType() that will return an XML object will all the type information. However, if you are uncomfortable working with the XML data, you can use the reflection API of AS3Commons-Reflect: http://www.as3commons.org
Here is an example:
var type:Type = Type.forClass(MyClass);
for each (var accessor:Accessor in type.accessors) {
if (accessor.writeable) {
// do something with writeable property
}
}
Also, if you happen to be doing a lot of calls to describeType, you should consider using the DescribeTypeCache for increased awesomeness (and also speed)
Here is an example of finding out from describeType if an object has a getter or setter.
keywords : detect reflectively getter setter discover
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 to tousdan's point - if you are going to do it a lot then create a cache. I don't like to include mx libraries if I don't have to so I cooked up 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 );
}
精彩评论