2

If all I have is an instance of an object, can I call a static method of its class? For fun, let's say I don't know what the name of the class is, only the name of the static method.

Can I do this? How do I do this?

jedierikb
  • 12,752
  • 22
  • 95
  • 166

3 Answers3

7

You can use the Object's constructor property to get a reference to that object's class object, you can then call the static variable from that class object

    package{
        import flash.display.Sprite;

        public class Test extends Sprite{

            public function Test(){
                var variable : A = new A();
                trace((variable as Object).constructor.a());

            }
        }
    }
    class A{
       static function a() : String{
           return "test";
       }
    }
T.W.R. Cole
  • 4,106
  • 1
  • 19
  • 26
SquareRootOf2
  • 393
  • 2
  • 5
5

There is a simpler way, but this assumes that the static functions exists.

var myclass:Class = getDefinitionByName("MyClass") as Class;
myclass["myStaticMethod"]();

It kinda surprised me that this syntax works.

loungerdork
  • 991
  • 11
  • 15
1

Get the class reference by it's instance.

var className:string = getQualifiedClassName(object); //returns the class name    
var classObj:Class = getDefinitionByName(className) as Class; //get a Class object

Also see this - How to get type of variable? and instantiate it?

Community
  • 1
  • 1
Chetan S
  • 23,637
  • 2
  • 63
  • 78
  • Just realized that you probably can't call a static method even with a reference to the Class object. I guess this answer is only halfway there. I don't have access to flex compiler, sorry. – Chetan S Jul 27 '09 at 21:43
  • Yes, you can, check out my answer above. – loungerdork Jul 28 '11 at 06:54