AS3:调用类的静态方法

编程入门 行业动态 更新时间:2024-10-27 00:25:10
本文介绍了AS3:调用类的静态方法 - 类和方法名是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个丑陋的问题。我有两个字符串变量(类名和静态方法)存储类的名称和它的静态方法我必须调用:

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) {} } } }

这是主题类:

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

它的工作原理只是完美。当你注释掉这个(9)线路问题:

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.)

在此先感谢。

推荐答案

原因是,编译器将去掉不必要的类 - 如果你没有一个明确提及类富的地方,它不会是present在最终的应用程序。

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.

更多推荐

AS3:调用类的静态方法

本文发布于:2023-11-11 23:51:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!