How to check if object has a property within namespace?
I want to check if object has a defined member within namespace. If was trying to use hasOwnProperty
method with QName, but it's not supported:
package {
import flexunit.framework.Assert;
public class ObjectTest extends Object {
public namespace some_public_namespace;
some_public_namespace var definedMember : String;
[Test]
public function testMemberWith开发者_开发问答inNamespace () : void {
// this should be elegant way... but actualy it doesn't work
try {
Assert.assertTrue( "Expect hasOwnProperty method work with QName", this.hasOwnProperty( new QName( some_public_namespace, "definedMember" ) ) );
} catch ( error : Error ) {
Assert.assertTrue( "hasOwnProperty method failed to work with QName", false );
}
// this is non elegant way that works
try {
this[ new QName( some_public_namespace, "definedMember" ) ];
Assert.assertTrue( "Expect no error", true );
} catch ( error : Error ) {
Assert.assertTrue( "Expect this line not to be runned", false );
}
try {
this[ new QName( some_public_namespace, "undefinedMember" ) ];
Assert.assertTrue( "Expect this line not to be runned", false );
} catch ( error : Error ) {
Assert.assertTrue( "Expect property doesn't exist", true );
}
}
}
}
As far as I can tell, the best way is to try to access the property.
For example, a utility function that does this:
public static function propertyIsAvailable(object:Object,
propertyName:Object):Boolean
{
var available:Boolean = false;
try {
var v:* = object[propertyName];
available = true;
} catch (e:Error) {
}
return available;
}
Then you can check for public as well as namespace properties:
var available:Boolean = propertyIsAvailable(object, "myPublicProperty");
var available:Boolean = propertyIsAvailable(object,
new QName(some_namespace, "myNamespaceProperty"));
精彩评论