Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3: call a static class method - class and method names are strings

I have an ugly problem. I have two string variables (className and staticMethod) store the name of a class and it's static method I have to call:

package {
 import flash.display.Sprite;
 import flash.utils.getDefinitionByName;
 import flash.utils.getQualifiedClassName;

 public class ClassPlay extends Sprite {

  public function ClassPlay() {
   new Foo();
   var className:String = 'Foo';
   var staticMethod:String = 'bar';
   var classClass:Class = getDefinitionByName(className) as Class;
   try {
    classClass[staticMethod]();
   } catch (e:Error) {}
  }
 }
}

This is the subject class:

package {
 public class Foo {
  public static function bar():void {trace('Foo.bar() was called.');}
 }
}

It works just perfectly. The problem when you comment out this (9th) line:

// new Foo();

Without this line it exits with an exception:

ReferenceError: Error #1065: Variable Foo is not defined.

How could I do this without that instantiation? If that is impossible, is there a way to instantiate the class from the string variable? Or if it's still a bad practice, how would you do that? (I have to work with those two unknown string variable.)

Thanks in advance.

like image 989
itarato Avatar asked Jan 11 '10 22:01

itarato


People also ask

What is a static method in Java?

In Java, a static method is a method that belongs to a class rather than an instance of a class. The method is accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that object of a class.

What's the purpose of static methods and static variables?

A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object. The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.

What are static variables in Java?

In Java, static variables are also called class variables. That is, they belong to a class and not a particular instance. As a result, class initialization will initialize static variables. In contrast, a class's instance will initialize the instance variables (non-static variables).

Whats the use of static variables?

Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.


1 Answers

The reason is that the compiler will strip out unnecessary classes - if you don't have an explicit reference to the class Foo somewhere, it won't be present in your final application.

You could the reference elsewhere and still force it to be loaded - for example, a static array of references to the classes.

like image 53
Anon. Avatar answered Nov 16 '22 12:11

Anon.