Send an unknown method call: Difference between revisions

add Ecstasy example
m (→‎{{header|Phix}}: syntax coloured)
(add Ecstasy example)
 
(7 intermediate revisions by 6 users not shown)
Line 12:
=={{header|AutoHotkey}}==
This object has 3 methods, and asks the user to name one to call. Instead of using Func(), one could use a class definition.
<langsyntaxhighlight AHKlang="ahk">obj := {mA: Func("mA"), mB: Func("mB"), mC: Func("mC")}
InputBox, methodToCall, , Which method should I call?
obj[methodToCall].()
Line 25:
MsgBox Method C
}
</syntaxhighlight>
</lang>
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat">(task=
( oracle
= (predicate="is made of green cheese")
Line 47:
& (SourceOfKnowledge..str$(generate !trueorlie))$!something
);
</syntaxhighlight>
</lang>
{{out|Example}}
<pre>{?} !task
Line 58:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
class Example
Line 79:
}
}
</syntaxhighlight>
</lang>
{{out}}
foo(5) = 47
Line 87:
$METHOD executes a named instance method for a specified instance of a designated class.
 
<langsyntaxhighlight lang="cos">Class Unknown.Example Extends %RegisteredObject
{
 
Line 100:
}
 
}</langsyntaxhighlight>
{{out|Examples}}
<pre>
Line 109:
This is bar
</pre>
 
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(import '[java.util Date])
(import '[clojure.lang Reflector])
 
(def date1 (Date.))
(def date2 (Date.))
(def method "equals")
 
;; Two ways of invoking method "equals" on object date1
;; using date2 as argument
 
;; Way 1 - Using Reflector class
;; NOTE: The argument date2 is passed inside an array
(Reflector/invokeMethod date1 method (object-array [date2]))
 
;; Way 2 - Using eval
;; Eval runs any piece of valid Clojure code
;; So first we construct a piece of code to do what we want (where method name is inserted dynamically),
;; then we run the code using eval
(eval `(. date1 ~(symbol method) date2))
</syntaxhighlight>
 
=={{header|Common Lisp}}==
Unknown methods are called just like any other function. Find the method-naming symbol using INTERN then call it with FUNCALL.
<langsyntaxhighlight lang="lisp">(funcall (intern "SOME-METHOD") my-object a few arguments)</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :object { :add @+ }
local :method :add
 
!. object! method 1 2</langsyntaxhighlight>
{{out}}
<pre>3</pre>
Line 126 ⟶ 150:
This example goes well with the object named <code>example</code> in [[Respond to an unknown method call#E]].
 
<langsyntaxhighlight lang="e">for name in ["foo", "bar"] {
E.call(example, name, [])
}</langsyntaxhighlight>
 
=={{header|Ecstasy}}==
Here's a simple example of a test module using its runtime type to search for methods by some name (specified on the the command line), grabbing the one by that name that requires no parameters, and dynamically invoking it:
 
<syntaxhighlight lang="ecstasy">
module test {
@Inject Console console;
 
void run(String[] args) {
String name = args.empty ? "foo" : args[0];
if (val mm := &this.actualType.multimethods.get(name),
val m := mm.methods.any(m -> m.ParamTypes.size == 0)) {
m.invoke(this, Tuple:());
} else {
console.print($"No such 0-parameter method: {name.quoted()}");
}
}
 
void foo() {
console.print("this is the foo() method");
}
 
void bar() {
console.print("this is the bar() method");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec test foo
this is the foo() method
x$ xec test bar
this is the bar() method
x$ xec test baz
No such 0-parameter method: "baz"
</pre>
 
=={{header|Elena}}==
ELENA 4.1 :
<langsyntaxhighlight lang="elena">import extensions;
class Example
Line 149 ⟶ 210:
console.printLine(methodSignature,"(",5,") = ",result)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 157 ⟶ 218:
=={{header|Factor}}==
Factor's object model is such that objects themselves don't contain methods — generic words do. So there is nothing different about invoking an unknown method than invoking an unknown word in general.
<langsyntaxhighlight lang="factor">USING: accessors kernel math prettyprint sequences words ;
IN: rosetta-code.unknown-method-call
 
Line 169 ⟶ 230:
! must specify vocab to look up a word
"rosetta-code.unknown-method-call"
lookup-word execute . ! 47</langsyntaxhighlight>
 
=={{header|Forth}}==
Line 177 ⟶ 238:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 188 ⟶ 249:
x p: 42 \ send the print message ( p: ) to x to verify the contents
 
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="basic">Type Example
foo As Integer Ptr
Declare Constructor (x As Integer)
End Type
 
Constructor Example(x As Integer)
This.foo = New Integer
*This.foo = 42 + x
End Constructor
 
Dim As Example result = 5
Print *result.foo
 
Sleep</syntaxhighlight>
{{out}}
<pre> 47</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 214 ⟶ 293:
// interpret first return value as int
fmt.Println(r[0].Int()) // => 42
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="grrovy">class Example {
def foo(value) {
"Invoked with '$value'"
Line 227 ⟶ 306:
def arg = "test value"
 
assert "Invoked with 'test value'" == example."$method"(arg)</langsyntaxhighlight>
 
==Icon and {{header|Unicon}}==
<langsyntaxhighlight Uniconlang="unicon">procedure main()
x := foo() # create object
x.m1() # static call of m1 method
Line 241 ⟶ 320:
method m1(x)
end
end</langsyntaxhighlight>
 
For more information on this see [[Respond_to_an_unknown_method_call#Icon_and_Unicon|Respond to an unknown method call]].
Line 247 ⟶ 326:
=={{header|Io}}==
String literal "foo" may be replaced by any expression resulting in a string.
<langsyntaxhighlight Iolang="io">Example := Object clone
Example foo := method(x, 42+x)
 
name := "foo"
Example clone perform(name,5) println // prints "47"</langsyntaxhighlight>
 
=={{header|J}}==
Line 259 ⟶ 338:
There are other methods as well, e.g., '''<tt>@.</tt>''','''<tt>`:</tt>''', and '''<tt>^:</tt>''', though these are designed to consume gerunds (pre-parsed ASTs) rather than strings (though, of course, a pre-processor can always be provided to convert strings into ASTs before feeding them to these operators).
 
'''Example''':<langsyntaxhighlight lang="j"> sum =: +/
prod =: */
count =: #
Line 279 ⟶ 358:
3
nameToDispatch (128!:2) 1 2 3
3</langsyntaxhighlight>
 
=={{header|Java}}==
Using reflection
<langsyntaxhighlight lang="java">import java.lang.reflect.Method;
 
class Example {
Line 300 ⟶ 379:
System.out.println(result); // prints "47"
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
String literal "foo" may be replaced by any expression resulting in a string
<langsyntaxhighlight lang="javascript">example = new Object;
example.foo = function(x) {
return 42 + x;
Line 310 ⟶ 389:
 
name = "foo";
example[name](5) # => 47</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">const functions = Dict{String,Function}(
"foo" => x -> 42 + x,
"bar" => x -> 42 * x)
 
@show functions["foo"](3)
@show functions["bar"](3)</langsyntaxhighlight>
 
{{out}}
Line 328 ⟶ 407:
=={{header|Kotlin}}==
When you try to compile the following program, it will appear to the compiler that the local variable 'c' is assigned but never used and a warning will be issued accordingly. You can get rid of this warning by compiling using the -nowarn flag.
<langsyntaxhighlight lang="scala">// Kotlin JS version 1.1.4-3
 
class C {
Line 340 ⟶ 419:
val f = "c.foo"
js(f)() // invokes c.foo dynamically
}</langsyntaxhighlight>
 
{{out}}
Line 348 ⟶ 427:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define mytype => type {
public foo() => {
return 'foo was called'
Line 358 ⟶ 437:
local(obj = mytype, methodname = tag('foo'), methodname2 = tag('bar'))
#obj->\#methodname->invoke
#obj->\#methodname2->invoke</langsyntaxhighlight>
{{out}}
<pre>foo was called
Line 364 ⟶ 443:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
-- ...
method = #foo
arg1 = 23
res = call(method, obj, arg1)</langsyntaxhighlight>
 
=={{header|Logtalk}}==
For this task, we first define a simple object with a single method:
<langsyntaxhighlight lang="logtalk">:- object(foo).
 
:- public(bar/1).
bar(42).
 
:- end_object.</langsyntaxhighlight>Second, we define another object that asks the user for a message to be sent to the first object:<langsyntaxhighlight lang="logtalk">
:- object(query_foo).
 
Line 388 ⟶ 467:
write(Message), nl.
 
:- end_object.</langsyntaxhighlight>After compiling and loading both objects, we can try:
| ?- query_foo::query.
Message: bar(X).
Line 395 ⟶ 474:
=={{header|Lua}}==
Don't forget to pass the object for methods!
<langsyntaxhighlight lang="lua">local example = { }
function example:foo (x) return 42 + x end
 
local name = "foo"
example[name](example, 5) --> 47</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Creates a dialog box where one can type a function (Sin, Cos, Tan ...) and then a second dialog box for a value.
<syntaxhighlight lang="text">ToExpression[Input["function? E.g. Sin",]][Input["value? E.g. 0.4123"]]</langsyntaxhighlight>
{{out}}
<pre>Input: Sin
Line 412 ⟶ 491:
 
 
<syntaxhighlight lang="matlab">
<lang Matlab>
funName = 'foo'; % generate function name
feval (funNAME, ...) % evaluation function with optional parameters
Line 418 ⟶ 497:
funName = 'a=atan(pi)'; % generate function name
eval (funName, 'printf(''Error\n'')')
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface Example : NSObject
Line 442 ⟶ 521:
}
return 0;
}</langsyntaxhighlight>
The <code>performSelector: ...</code> methods can only be used with methods with 0 - 2 object arguments, and an object or <code>void</code> return type. For all other calls, one can create an <code>NSInvocation</code> object and invoke it, or directly call one of the <code>objc_msgSend</code> family of runtime functions.
 
Line 448 ⟶ 527:
 
A method object can be retrieved from its name using asMethod.
<langsyntaxhighlight Oforthlang="oforth">16 "sqrt" asMethod perform</langsyntaxhighlight>
Others :
Line 456 ⟶ 535:
 
A generic way to search a word into the dictionary in to use find method :
<langsyntaxhighlight Oforthlang="oforth">16 "sqrt" Word find perform</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">foo()=5;
eval(Str("foo","()"))</langsyntaxhighlight>
 
=={{header|Pascal}}==
 
Works with FPC (tested with version 3.2.2).
 
In the simplest case, when the methods are procedures without parameters, it might look something like this (note that these methods are currently required to have PUBLISHED visibility):
<syntaxhighlight lang="pascal">
program Test;
{$mode objfpc}{$h+}
uses
SysUtils;
 
type
TProc = procedure of object;
 
{$push}{$m+}
TMyObj = class
strict private
FName: string;
public
constructor Create(const aName: string);
property Name: string read FName;
published
procedure Foo;
procedure Bar;
end;
{$pop}
 
constructor TMyObj.Create(const aName: string);
begin
FName := aName;
end;
 
procedure TMyObj.Foo;
begin
WriteLn(Format('This is %s.Foo()', [Name]));
end;
 
procedure TMyObj.Bar;
begin
WriteLn(Format('This is %s.Bar()', [Name]));
end;
 
procedure CallByName(o: TMyObj; const aName: string);
var
m: TMethod;
begin
m.Code := o.MethodAddress(aName);
if m.Code <> nil then begin
m.Data := o;
TProc(m)();
end else
WriteLn(Format('Unknown method(%s)', [aName]));
end;
 
var
o: TMyObj;
 
begin
o := TMyObj.Create('Obj');
CallByName(o, 'Bar');
CallByName(o, 'Foo');
CallByName(o, 'Baz');
o.Free;
end.
</syntaxhighlight>
 
{{out}}
<pre>
This is Obj.Bar()
This is Obj.Foo()
Unknown method(Baz)
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">package Example;
sub new {
bless {}
Line 474 ⟶ 626:
package main;
my $name = "foo";
print Example->new->$name(5), "\n"; # prints "47"</langsyntaxhighlight>
 
=={{header|Phix}}==
Not specifically anything to do with objects, but you can construct routine names at runtime:
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">Hello</span><span style="color: #0000FF;">()</span>
Line 490 ⟶ 642:
<span style="color: #7060A8;">call_proc</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #000000;">erm</span><span style="color: #0000FF;">),{})</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
class Example {
function foo($x) {
Line 507 ⟶ 659:
// alternately:
echo call_user_func(array($example, $name), 5), "\n";
?></langsyntaxhighlight>
 
=={{header|Picat}}==
For functions use <code>apply/n</code> and for predicates <code>call/n</code>. The name of the function/predicate must be an atom and strings must be converted to atom, e.g. with <code>to_atom/1</code>.
<syntaxhighlight lang="picat">go =>
println("Function: Use apply/n"),
Fun = "fib",
A = 10,
% Convert F to an atom
println(apply(to_atom(Fun),A)),
nl,
 
println("Predicate: use call/n"),
Pred = "pyth",
call(Pred.to_atom,3,4,Z),
println(z=Z),
 
% Pred2 is an atom so it can be used directly with call/n.
Pred2 = pyth,
call(Pred.to_atom,13,14,Z2),
println(z2=Z2),
nl.
 
% A function
fib(1) = 1.
fib(2) = 1.
fib(N) = fib(N-1) + fib(N-2).
 
% A predicate
pyth(X,Y,Z) =>
Z = X**2 + Y**2.</syntaxhighlight>
 
{{out}}
<pre>Function: Use apply/n
55
 
Predicate: use call/n
z = 25
z2 = 365</pre>
 
=={{header|PicoLisp}}==
This can be done with the '[http://software-lab.de/doc/refS.html#send send]' function.
<langsyntaxhighlight PicoLisplang="picolisp">(send (expression) Obj arg1 arg2)</langsyntaxhighlight>
 
=={{header|Pike}}==
with [] instead of -> a string can be used to name a method:
<langsyntaxhighlight Pikelang="pike">string unknown = "format_nice";
object now = Calendar.now();
now[unknown]();</langsyntaxhighlight>
 
=={{header|PowerShell}}==
A random method using a random number:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$method = ([Math] | Get-Member -MemberType Method -Static | Where-Object {$_.Definition.Split(',').Count -eq 1} | Get-Random).Name
$number = (1..9 | Get-Random) / 10
Line 532 ⟶ 723:
 
$output | Format-List
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 542 ⟶ 733:
=={{header|Python}}==
String literal "foo" may be replaced by any expression resulting in a string
<langsyntaxhighlight lang="python">class Example(object):
def foo(self, x):
return 42 + x
 
name = "foo"
getattr(Example(), name)(5) # => 47</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang qi>
(define foo -> 5)
 
Line 557 ⟶ 748:
 
(execute-function "foo")
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define greeter
Line 573 ⟶ 764:
(define unknown 'hello)
(dynamic-send greeter unknown "World")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Just for the fun of it, we'll mix in an anonymous role into an integer instead of defining a class.
<syntaxhighlight lang="raku" perl6line>my $object = 42 but role { method add-me($x) { self + $x } }
my $name = 'add-me';
say $object."$name"(5); # 47</langsyntaxhighlight>
The double quotes are required, by the way; without them the variable would be interpreted as a hard ref to a method.
 
Line 586 ⟶ 777:
You may replace :foo, :bar or "bar" with any expression that returns a Symbol or String.
 
<langsyntaxhighlight lang="ruby">class Example
def foo
42
Line 599 ⟶ 790:
Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3
args = [1, 2]
Example.new.send( "bar", *args ) { |x,y| x+y } # => 3</langsyntaxhighlight>
 
Object#send can also call protected and private methods, skipping the usual access checks. Ruby 1.9 adds Object#public_send, which only calls public methods.
 
{{works with|Ruby|1.9}}
<langsyntaxhighlight lang="ruby">class Example
private
def privacy; "secret"; end
Line 614 ⟶ 805:
e.public_send :publicity # => "hi"
e.public_send :privacy # raises NoMethodError
e.send :privacy # => "secret"</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">class Example {
def foo(x: Int): Int = 42 + x
}
Line 628 ⟶ 819:
assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.")
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Example {
method foo(x) {
42 + x
Line 641 ⟶ 832:
 
say obj.(name)(5) # prints: 47
say obj.method(name)(5) # =//=</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">Object subclass: #Example.
 
Example extend [
Line 652 ⟶ 843:
symbol := 'foo:' asSymbol. " same as symbol := #foo: "
 
Example new perform: symbol with: 5. " returns 47 "</langsyntaxhighlight>
The <code>perform:with:with:</code> family of methods exist for methods with 0 - 2 (3 in [[GNU Smalltalk]]) arguments. For methods with more arguments, use <code>perform:withArguments:</code>, which takes an array of arguments.
 
Line 664 ⟶ 855:
The first case is used for interfacing with legacy Objective-C libraries. Objective-C is heavily dynamic with Smalltalk-style message passing. So Swift must be able to participate in this.
 
<langsyntaxhighlight lang="swift">import Foundation
 
class MyUglyClass: NSObject {
Line 675 ⟶ 866:
let someObject: NSObject = MyUglyClass()
 
someObject.perform(NSSelectorFromString("myUglyFunction"))</langsyntaxhighlight>
 
{{out}}
Line 685 ⟶ 876:
One of Swift's goals is to able to effectively bridge to dynamic languages such as Python and JavaScript. In order to facilitate more natural APIs, Swift provides the <code>@dynamicCallable</code> and <code>@dynamicMemberLookup</code> attributes which allow for runtime handling of method calls.
 
<langsyntaxhighlight lang="swift">@dynamicCallable
protocol FunDynamics {
var parent: MyDynamicThing { get }
Line 769 ⟶ 960:
.subtract(adding: 10, subtracting: 14)
 
print(thing.n)</langsyntaxhighlight>
 
{{out}}
Line 777 ⟶ 968:
=={{header|Tcl}}==
Method names are really just strings, i.e., ordinary values that can be produced by any mechanism:
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
oo::class create Example {
method foo {} {return 42}
Line 790 ⟶ 981:
for {set i 1} {$i <= 4} {incr i} {
$eg $i ...
}</langsyntaxhighlight>
{{out|The above produces this output}}
42
Line 799 ⟶ 990:
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "meta" for Meta
class Test {
Line 812 ⟶ 1,003:
for (method in ["foo", "bar"]) {
Meta.eval("test.%(method)()")
}</langsyntaxhighlight>
 
{{out}}
Line 821 ⟶ 1,012:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">name:="len"; "this is a test".resolve(name)() //-->14</langsyntaxhighlight>
 
{{omit from|Ada}}
162

edits