Get AS3 instance method reference from Class object - actionscript-3

class Foo {
public function bar():void { ... }
}
var clazz:Class = Foo;
// ...enter the function (no Foo literal here)
var fun:Function = clazz["bar"]; // PROBLEM: returns null
// later
fun.call(new Foo(), ...);
What is the correct way to do the above? The Java equivalent of what I want to do is:
Method m = Foo.class.getMethod("bar", ...);
m.invoke(new Foo(), ...);
Actual code (with workaround):
class SerClass {
public var className:String;
public var name:String;
private var ser:String = null;
private var unser:Function = null;
public function SerClass(clazz:Class):void {
var type:XML = describeType(clazz);
className = type.#name;
// determine name
name = type.factory.metadata.(#name=="CompactType").arg.(#key=="name").#value;
// find unserializer
var mdesc:XML = XML(type.method.metadata.(#name=="Unserialize")).parent();
if (mdesc is XML) {
unser = clazz[mdesc.#name];
}
// find serializer
var sdesc:XML = XML(type.factory.method.metadata.(#name=="Serialize")).parent();
if (sdesc is XML) {
ser = sdesc.#name;
}
}
public function serialize(obj:Object, ous:ByteArray):void {
if (ser == null) throw new Error(name + " is not serializable");
obj[ser](ous);
}
public function unserialize(ins:ByteArray):Object {
if (unser == null) throw new Error(name + " is not unserializable");
return unser.call(null, ins);
}
}

Here the function bar only exist when your class is instanciated :
var foo:Foo = new Foo()
var fun:Function = foo.bar // <-- here you can get the function from the new instance
if you want to access it directlty you have to make it static:
class Foo {
public static function bar():void{ ... }
}
now you can access your function from the class Foo:
var fun:Function = Foo.bar
or
var clazz:Class = Foo
var fun:Function = clazz["bar"]

I am not sure about what you are intending to do.
However AS3Commons, especially the reflect package have API's that let you work with methods, instances and properties of a class.
There are also API methods to create instances of certain class types on the fly and call their respective methods.
Cheers

It's not
fun.call(new Foo(), ...);
Use instead since no parameters are required for the function
fun.call(clazz);
The first parameter as specified by adobe docs.
An object that specifies the value of thisObject within the function body.
[EDIT]
Forgot to point out you have to instantiate a non-static class with the "new" keyword.
var clazz:Class = new Foo();
[EDIT2]
Ok I played around and think I got what you want.
base.as
package{
public class Base {
public function Base() {
trace('Base constructor')
}
public function someFunc( ){
trace('worked');
}
}
}
//called with
var b:Base = new Base( );// note I am not type casting to Class
var func:Function = b.someFunc;
func.call( );

My workaround is to store the function name instead of the Function object.
var fun:String = "bar";
// later...
new Foo()[fun](...);

Related

Classes vs Objects? as3

I creat two people that are instances of the Person Class
var personOne = new Person;
var personTwo = new Person;
later I create an Object called Chuck;
var Chuck = {age:32, name:"Chuck"}
Now I want to make personOne be a "person" with the properties of "chuck:Object";
Cannot convert Object to Display Object. // Output
If you want to set properties of an object when it is created, you can let the constructor accept them as parameters.
For example:
package
{
public class Person
{
private var _age:uint, _name:String;
public function Person (age:uint, name:String)
{
_age = age;
_name = name;
}
}
}
You use it like so:
var chuck:Person = new Person(32, "Chuck");
This is probably not what you need, but it is what you asked.
var personOne :Person = new Person();
var object:Object = { age:23, name:"efefw" };
for (var prop:String in object)
{
personOne[prop] = object[prop];
}
This will only work for public properties.

How to call a static function on an ActionScript object's ancestor class?

The Ancestor class does, indeed, have a function called (for the sake of example) "foo".
public static function callAncestorStaticMethod() : void
{
var ancestorClassName : String = getQualifiedSuperclassName(Descendant);
var ancestorClass : Class = Class(getDefinitionByName(ancestorClassName));
ancestorClass.foo(); // <---- runtime error here: foo is not a function
}
Examining ancestorClass finds it an Object with no visible properties (ancestorClass.prototype does not either).
So, how do I call a static function on a class when I only have its name as a string at runtime ?
I was able to call a static function in the superclass using the following code:
var c:ChildClass = new ChildClass();
var s:String = getQualifiedSuperclassName(c);
var cl:Class = getDefinitionByName(s) as Class;
cl.foo.call();
//cl["foo"].call();
A Class object has all of the static properties and methods of the Class, so this should be reliable. cl.foo returns a Function object that you can then .call().
You can get a reference to the instance's own class using the constructor property, but to access the ancestor classes, you have to use describeType and getDefinitionByName. These are powerful, but costly - so make sure you don't overuse this:
function callStaticAncestorProperty( instance:Object, staticProperty:String ):* {
var type:XML = describeType( instance );
var ret:* = instance.constructor[staticProperty];
for each(var extend:XML in type.extendsClass)
ret = ret ? ret : getStaticPropertyOrUndefined( extend, staticProperty );
return ret;
}
function getStaticPropertyOrUndefined( extend:XML, staticProperty:String ):* {
var clazz:Class = getDefinitionByName( extend.#type.toString().replace( "::", "." ) ) as Class;
return clazz[staticProperty] ? clazz[staticProperty] : undefined;
}
This checks if the class itself has the property, and then iterates over each super type. Note that the first value to be found will be returned, i.e. if both the subclass and a super class have this property, that of the subclass will be returned.
Edit
I only just realized you were asking about method calls, not properties. That works pretty much the same way:
function callStaticAncestorMethod( instance:Object, staticMethod:String ):void {
var type:XML = describeType( instance );
var method:Function = instance.constructor[staticMethod];
for each(var extend:XML in type.extendsClass)
method = method ? method : getStaticMethodOrUndefined( extend, staticMethod );
if (method) method();
}
function getStaticMethodOrUndefined( extend:XML, staticMethod:String ):Function {
var clazz:Class = getDefinitionByName( extend.#type.toString().replace( "::", "." ) ) as Class;
return clazz[staticMethod] ? clazz[staticMethod] : undefined;
}
Or (Based on Sam DeHaan answer's):
If Superclass and Descendant have both a String id property...
(getDefinitionByName(getQualifiedSuperclassName(Descendant))as Class).foo();
trace((getDefinitionByName(getQualifiedSuperclassName(Descendant))as Class).id);
Where :
// trace (Descendant.id);
// if private : compile time Error.
// 1178: Attempted access of inaccessible property id through a reference with static type Class.
var d:Descendant;
trace((getDefinitionByName("Descendant") as Class).id);
// output undefined if private : the value if public. But don't throw compile time Error.
(getDefinitionByName("Descendant") as Class).foo();
// Call static foo() from Descendant. // Throw a compile time Error if method is private
// trace (Superclass.id);
// if private : compile time Error.
// 1178: Attempted access of inaccessible property id through a reference with static type Class.
var s:Superclass;
trace((getDefinitionByName("Superclass") as Class).id);
// output undefined if private : the value if public. But don't throw compile time Error.
(getDefinitionByName("Superclass") as Class).foo();
// Call static foo() from Superclass. // Throw a compile time Error if method is private

How to instantiate an array of custom classes in Action Script 3.0

I'm new to AS3 and I'm getting this error while trying to implement OO style code.
Incorrect number of arguments. Expected no more than 0.
When I try to:
var countries:Country = new Country(10);
Normally this would work in Java or C++, so I'm not sure what's up!?
Here is my custom class.
package {
public class Country {
var cName:String = "noName";
public function Country() {
// constructor code
}
public function setName(n:String):void {
cName = n;
}
public function getName():String {
return cName;
}
}
}
You are passing 10 to the constructor, which is not what you want to do. To instantiate an array of instances, try something like this:
var countries:Array = []
var country:Country;
for (var i:uint = 0; i < 10; i++) {
country = new Country()
country.setName("Country_" + i);
countries.push(country)
}
your constructor function public function Country() {} not have an argument, but you give 10, must go wrong.
ActionScript's array not like c++, don't need element type <Country>
you want to save class in array is simple: var arr:Array = [new Country()]

ActionScript - Determine If Value is Class Constant

i'd like to throw an argument error if a particular function doesn't work without a passed value that also happens to be a public constant of the class containing the function.
is there anyway to determine if a class owns a public constant instead of having to iterate thru all of them?
something like this:
public static const HALIFAX:String = "halifax";
public static const MONTREAL:String = "montreal";
public static const TORONTO:String = "toronto";
private var cityProperty:String;
public function set city(value:String):void
{
if (!this.hasConstant(value))
throw new ArgumentError("set city value is not applicable.");
cityProperty = value;
}
public function get city():Strig
{
return cityProperty;
}
currently, for this functionality i have to write the city setter function like this:
public function set city(value:String):void
{
if (value != HALIFAX && value != MONTREAL && value != TORONTO)
throw new ArgumentError("set city value is not applicable.");
cityProperty = value;
}
is this the only way to accomplish this task?
Yes, if you use reflections:
private var type:Class;
private var description:XML;
private function hasConstant (str : String ) : Boolean
{
if (description == null)
{
type = getDefinitionByName (getQualifiedClassName (this)) as Class;
description = describeType (type);
}
for each ( var constant:XML in description.constant)
{
if (type[constant.#name] == str) return true;
}
return false;
}
Note that for this to work, all constants must always be String objects declared public static const.
I was looking for an answer to this question myself and found it annoying that hasOwnProperty() did not work for static properties. Turns out though, that if you cast your class to a Class object, it does work.
Here's an example:
public final class DisplayMode
{
public static const one: String = "one";
public static const two: String = "two";
public static const three: String = "three";
public static function isValid(aDisplayMode: String): Boolean {
return Class(DisplayMode).hasOwnProperty(aDisplayMode);
}
}
I owe this solution to jimmy5804 from this discussion, so hats off to him.
You should be able to use bracket notation to do this. For example:
var foo:Sprite = new Sprite();
foo.rotation = 20;
trace( foo["x"], foo["rotation"]); // traces "0 20"
or more specific to your case:
var bar:String = "rotation";
trace( foo[bar] ); // traces "20"
The only thing you have to look out for here, is that the bracket accessor will throw a ReferenceError if you ask for an object property that isn't there, such as:
trace ( foo["cat"] ); // throws ReferenceError
But it will not throw if you are asking for a static property:
trace ( Sprite["cat"] ); // traces "undefined"
So in your case you might try:
if ( this[value] == undefined ) {
throw new ArgumentError("set city value is not applicable.");
}
EDIT:
Sorry, I was confusing the const's names with their values.
For this to work on your problem you would have to make the String value the same as the const's name, so for example:
public static const HALIFAX:String = "HALIFAX";
then you could use the query as described above and it would give you the desired result.

AS3 Custom Object to ByteArray then to Custom Object

Having problem reading bytearray of custom objects. Any help is appreciated
public class CustomObject extends Object {
public function CustomObject() {
public var _x:Number = 100
public var _y:Number = 10
public var _z:Number = 60
}
}
var cObj:CustomObject = new CustomObject()
var bytes:ByteArray = new ByteArray()
bytes.writeObject(cObj)
bytes.compress()
//read
try { bytes.uncompress() } catch (e:Error) { }
var obj:CustomObject = bytes.readObject() as CustomObject
trace(obj) // null why?!
trace(obj._z) // Obviously - TypeError: Error #1009: Cannot access a property or method of a null object reference.
What you want to do is use the registerClassAlias method to register type information along with the data. That way Flash will know how to serialize/deserialize your object. Here's some sample code from Adobe's documentation:
registerClassAlias("com.example.eg", ExampleClass);
var eg1:ExampleClass = new ExampleClass();
var ba:ByteArray = new ByteArray();
ba.writeObject(eg1);
ba.position = 0;
var eg2:* = ba.readObject();
trace(eg2 is ExampleClass); // true
It should be noted that all types that should be serialized must be registered for the type information to be saved. So if you have another type that is referenced by your type, it too must be registered.
Your CustomObject class is wrong , it should throw an error actually , it should be this instead
public class CustomObject
{
public var _x:Number = 100
public var _y:Number = 10
public var _z:Number = 60
public function CustomObject()
{
}
}
Edit:
Sounds like macke has a point, because this works...
//read
try { bytes.uncompress() } catch (e:Error) { }
var obj:Object = bytes.readObject();
trace(obj) // [object Object]
trace(obj._z) // 60
Look at object that ByteArray.readObject() returns. You'll probably see that all properties are there, but type information is lost. So, you can solve this by creating some
public static function fromObject(value:Object):CustomObject {
var result:CustomObject = new CustomObject();
result._x = value._x;
//and so on...
return result;
}
To serialize custom classes to the ByteArray, you must put registerClassAlias in the constructor of the class calling the byteArray.writeObject() function.
If you don't, your custom class will be serialized as Object type. I was calling registerClassAlias in the serialize function below and my custom class keeps getting serialized as Object until I moved the registerClassAlias to the constructor.
public class MyClass{
public function MyClass(){
registerClassAlias("com.myclass", MyClass); // Ok, serializes as MyClass
serialize( new MyClass() );
}
private function serialize( _c:MyClass ){
var byteArray:ByteArray = new ByteArray();
byteArray.writeObject( _c );
//registerClassAlias("com.myclass", MyClass); Not ok, serialized as Object
EncryptedLocalStorage.setItem('key', byteArray);
}
}