Respond to an unknown method call: Difference between revisions
Content added Content deleted
(added Fantom example) |
(updated Fantom solution to trap only unknown methods) |
||
Line 128: | Line 128: | ||
=={{header|Fantom}}== |
=={{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 |
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 throws an exception if the method/field is not known. This exception can be caught, and processed specially: |
||
<lang fantom> |
<lang fantom> |
||
class A |
class A |
||
{ |
{ |
||
public Void doit (Int n) |
|||
{ |
|||
echo ("known function called on $n") |
|||
} |
|||
// override the 'trap' method, which catches dynamic invocations of methods |
// override the 'trap' method, which catches dynamic invocations of methods |
||
override Obj? trap(Str name, Obj?[]? args := null) |
override Obj? trap(Str name, Obj?[]? args := null) |
||
{ |
{ |
||
try |
|||
⚫ | |||
{ |
|||
return super.trap(name, args) |
|||
} |
|||
catch (UnknownSlotErr err) |
|||
{ |
|||
⚫ | |||
return null |
|||
} |
|||
} |
} |
||
} |
} |
||
Line 147: | Line 159: | ||
a := A() |
a := A() |
||
// note the dynamic dispatch |
// note the dynamic dispatch |
||
a->doit (1) |
|||
a->methodName (1, 2, 3) |
a->methodName (1, 2, 3) |
||
} |
} |
||
Line 155: | Line 168: | ||
<pre> |
<pre> |
||
$ fan unknown-method.fan |
$ fan unknown-method.fan |
||
known function called on 1 |
|||
In trap, you called: methodName with args 1,2,3 |
In trap, you called: methodName with args 1,2,3 |
||
</pre> |
</pre> |
||
In normal usage, the trap method tries to locate the named method using reflection on the current class. |
|||
=={{header|J}}== |
=={{header|J}}== |