Respond to an unknown method call: Difference between revisions

updated 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 canthrows thusan exception if the method/field is not known. This exception can be caught, and processed specially:
 
<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 null{
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>
 
In normal usage, the trap method tries to locate the named method using reflection on the current class.
 
=={{header|J}}==
342

edits