views:

514

answers:

2

I am overriding the addItem() function of an array collection and I would like to detect if the added item implements a particular interface.

Previously I used the, is operator to detect the class type, but now that I am using an interface for classes I would rather test to see if the object implements the interface.

I expect I could just try and cast the object as the interface and see if it's not null. Is this the best way to do it?

I could also just create a new addFunction() that only accepts objects of the interface type.

+9  A: 

You can still use is to test for an interface.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768" creationComplete="application1_creationCompleteHandler(event)">
    <fx:Script>
     <![CDATA[
      import mx.events.FlexEvent;
      public var test:TestInterface = new TestInterface() //implements ITestInterface


      protected function application1_creationCompleteHandler(event:FlexEvent):void
      {
       trace(test is ITestInterface); //true
      }

     ]]>
    </fx:Script>
</s:Application>
Joel Hooks
Thanks Joel, was rather lazy of me, but I wanted to know the right way to do it, rather than finding something that worked but may have been bad practice.
robmcm
Good choice! Can you add "in AS3" to the end of the title?
Joel Hooks
+2  A: 

To add to the answer of Joel: if you want more information about the interfaces a class implements (and its subclasses, parent classes, etc), the AS3Commons library has a ClassUtils class that has a number of convenience methods.

Christophe Herreman