Respond to an unknown method call: Difference between revisions
Respond to an unknown method call (view source)
Revision as of 13:03, 21 February 2011
, 13 years agoupdated Fantom solution to trap only unknown methods
(added Fantom example) |
(updated Fantom solution to trap only unknown methods) |
||
Line 128:
=={{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. This method looks up the given method name, and
<lang fantom>
class A
{
public Void doit (Int n)
{
echo ("known function called on $n")
}
// override the 'trap' method, which catches dynamic invocations of methods
override Obj? trap(Str name, Obj?[]? args := null)
{
try
echo ("In trap, you called: " + name + " with args " + args.join(","))▼
return super.trap(name, args)
}
catch (UnknownSlotErr err)
{
▲ echo ("In trap, you called: " + name + " with args " + args.join(","))
return null
}
}
}
Line 147 ⟶ 159:
a := A()
// note the dynamic dispatch
a->doit (1)
a->methodName (1, 2, 3)
}
Line 155 ⟶ 168:
<pre>
$ fan unknown-method.fan
known function called on 1
In trap, you called: methodName with args 1,2,3
</pre>
=={{header|J}}==
|