Mr. Boy
Mr. Boy

Reputation: 63816

Get current class+method name in AS3

I wondered if there is a simple way I have have a snippet which traces the name of a method when called. I found className which is half-way there, but not something for the method... a 1-line trace(...) is what I'm after so I avoid typing the method name and leaving myself open to mistakes. This is for testing the order things happen, when I don't want to step through in the debugger.

Upvotes: 0

Views: 2442

Answers (2)

Nicholas
Nicholas

Reputation: 5520

    public static function getCurrentClassName(c:Object):String
    {
        var cString:String = c.toString();
        var cSplittedFirst:Array = cString.split('[object ');
        var cFirstString:String = String(cSplittedFirst[1]);
        var cSplittedLast:Array = cFirstString.split(']');
        var cName:String = cSplittedLast.join('');

        return cName;
    }

Used to check if a certain class is constructed or not.

Usage (here I put the code in the main class):

trace('[DEBUG]: '+ClassData.getCurrentClassName(this)+' constructed.');

trace returns:

[DEBUG]: Main constructed.

Upvotes: 0

Patrick
Patrick

Reputation: 15717

If you have compiled your swf with debug information and use the debug version of the player you can take a look at getStackTrace property from the Error object:

Quick example:

    public function getCallingInfos():Object{
        var tmp:Array=new Error().getStackTrace().split("\n");
        tmp=tmp[2].split(" ");
        tmp=tmp[1].split("/");
        return {namespaceAndClass:tmp[0], method:tmp[1]};
    }

    var infos:Object=getCallingInfos();
    trace(infos.namespaceAndClass, infos.method);

Upvotes: 3

Related Questions