Respond to an unknown method call: Difference between revisions
Respond to an unknown method call (view source)
Revision as of 02:14, 21 February 2011
, 13 years agoadded Fantom example
No edit summary |
(added Fantom example) |
||
Line 125:
a they_can_too: "eat" and: "walk"
</lang>
=={{header|Fantom}}==
In Fantom, you can call methods statically or dynamically. Static calls to methods will be checked at compile time. Dynamic method calls (indicated by an <code>instance->method</code> syntax) are run through a "[http://fantom.org/doc/sys/Obj.html#trap trap]" method at run time, and can thus be caught:
<lang fantom>
class A
{
// override the 'trap' method, which catches dynamic invocations of methods
override Obj? trap(Str name, Obj?[]? args := null)
{
echo ("In trap, you called: " + name + " with args " + args.join(","))
return null
}
}
class Main
{
public static Void main ()
{
a := A()
// note the dynamic dispatch
a->methodName (1, 2, 3)
}
}
</lang>
Output:
<pre>
$ fan unknown-method.fan
In trap, you called: methodName with args 1,2,3
</pre>
In normal usage, the trap method tries to locate the named method using reflection on the current class.
=={{header|J}}==
|