Reflection/List methods: Difference between revisions

Add Ecstasy example
mNo edit summary
(Add Ecstasy example)
 
(9 intermediate revisions by 5 users not shown)
Line 18:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Reflection;
 
Line 43:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 61:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">
; Including listing private methods in the clojure.set namespace:
=> (keys (ns-interns 'clojure.set))
Line 68:
; Only public:
=> (keys (ns-publics 'clojure.set))
(union map-invert join select intersection superset? index subset? rename rename-keys project difference)</langsyntaxhighlight>
 
=={{header|D}}==
D allows you to perform compile-time reflection for code generation, such as printing a list of the functions in a struct or class.
<langsyntaxhighlight Dlang="d">struct S {
bool b;
 
Line 104:
printMethods!S;
printMethods!C;
}</langsyntaxhighlight>
 
{{out}}
Line 118:
opEquals
factory</pre>
 
=={{header|Ecstasy}}==
For any object, the type of that object provides access to its methods and functions:
 
<syntaxhighlight lang="ecstasy">
module test {
void run() {
@Inject Console console;
 
String[] names = &this.actualType.multimethods.keys.toArray();
console.print($"Method/function names on {this}: {names}");
 
Method[] methods = &this.actualType.methods;
console.print($"The methods of {this}: {methods}");
 
Function[] functions = &this.actualType.functions;
console.print($"The functions of {this}: {functions}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec test
Method/function names on test: [toString, makeImmutable, to, estimateStringLength, appendTo, exTo, toEx, exToEx, isModuleImport, classForName, typeForName, run, hashCode, maxOf, notGreaterThan, compare, equals, minOf, notLessThan]
The methods of test: [String toString(), immutable Object makeImmutable(), Range<Orderable> to(Orderable that), Int estimateStringLength(), Appender<Char> appendTo(Appender<Char> buf), Range<Orderable> exTo(Orderable that), Range<Orderable> toEx(Orderable that), Range<Orderable> exToEx(Orderable that), conditional Module isModuleImport(), conditional Class classForName(String name), conditional Type typeForName(String name), void run()]
The functions of test: [Int hashCode(Type<Package> CompileType, CompileType value), CompileType maxOf(Type<Orderable> CompileType, CompileType value1, CompileType value2), CompileType notGreaterThan(Type<Orderable> CompileType, CompileType value1, CompileType value2), Ordered compare(Type<Const> CompileType, CompileType value1, CompileType value2), Boolean equals(Type<Package> CompileType, CompileType value1, CompileType value2), CompileType minOf(Type<Orderable> CompileType, CompileType value1, CompileType value2), CompileType notLessThan(Type<Orderable> CompileType, CompileType value1, CompileType value2)]
</pre>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'dynamic;
import extensions;
Line 136 ⟶ 164:
var o := new MyClass();
o.__getClass().__getMessages().forEach::(p)
{
console.printLine("o.",p)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 148 ⟶ 176:
o.myMethod1[1]
o.myMethod2[2]
o.#cast[1]
</pre>
 
=={{header|Factor}}==
In Factor, methods are contained in generic words rather than objects, while methods specialize on a class. Therefore, the programmer must decide whether they want the list of methods in a generic word, or the list of methods that specialize on a class. Luckily, the <tt>methods</tt> word can do either depending on what type you give it (a word or a class). The returned sequence contains first-class word values suitable for executing.
<langsyntaxhighlight lang="factor">USING: io math prettyprint see ;
 
"The list of methods contained in the generic word + :" print
Line 159 ⟶ 186:
 
"The list of methods specializing on the fixnum class:" print
fixnum methods .</langsyntaxhighlight>
{{out}}
<pre>
Line 209 ⟶ 236:
M\ fixnum u>=
}
</pre>
 
=={{header|Frink}}==
Frink allows you to list the methods of a Frink-based or Java-based object with the <CODE>methods[obj]</CODE> function.
<syntaxhighlight lang="frink">a = new array
methods[a]</syntaxhighlight>
{{out}}
<pre>[
pushAll[arg1],
insert[arg1, arg2],
indexOf[arg1],
indexOf[arg1, arg2],
removeAll[arg1],
shuffle[],
dimensions[],
push[arg1],
pop[],
contains[arg1],
subsets[],
subsets[arg1, arg2],
transpose[],
isEmpty[],
lexicographicPermute[],
lexicographicPermute[arg1],
popFirst[],
clear[],
peek[],
shallowCopy[],
pushFirst[arg1],
removeValue[arg1],
timSort[],
timSort[arg1],
timSort[arg1, arg2],
permute[],
removeLen[arg1, arg2],
lastIndexOf[arg1],
lastIndexOf[arg1, arg2],
combinations[arg1],
removeRandom[],
remove[arg1],
remove[arg1, arg2]]
</pre>
 
Or, for a Java object:
<syntaxhighlight lang="frink">f = newJava["java.io.File", "."]
methods[f]</syntaxhighlight>
{{out}}
<pre>[
boolean equals[java.lang.Object arg1],
long length[],
java.lang.String toString[],
int hashCode[],
int compareTo[java.lang.Object arg1],
int compareTo[java.io.File arg1],
java.lang.String getName[],
java.lang.String[] list[java.io.FilenameFilter arg1],
java.lang.String[] list[],
java.lang.String getParent[],
boolean isAbsolute[],
boolean delete[],
boolean setReadOnly[],
boolean canRead[],
java.lang.String getPath[],
java.net.URI toURI[],
java.net.URL toURL[],
java.io.File getParentFile[],
java.lang.String getAbsolutePath[],
java.io.File getAbsoluteFile[],
java.lang.String getCanonicalPath[],
java.io.File getCanonicalFile[],
boolean isDirectory[],
boolean canWrite[],
boolean exists[],
boolean isFile[],
boolean isHidden[],
long lastModified[],
boolean createNewFile[],
void deleteOnExit[],
java.io.File[] listFiles[java.io.FileFilter arg1],
java.io.File[] listFiles[],
java.io.File[] listFiles[java.io.FilenameFilter arg1],
boolean mkdir[],
boolean mkdirs[],
boolean renameTo[java.io.File arg1],
boolean setLastModified[long arg1],
boolean setWritable[boolean arg1],
boolean setWritable[boolean arg1, boolean arg2],
boolean setReadable[boolean arg1],
boolean setReadable[boolean arg1, boolean arg2],
boolean setExecutable[boolean arg1, boolean arg2],
boolean setExecutable[boolean arg1],
boolean canExecute[],
java.io.File[] listRoots[],
long getTotalSpace[],
long getFreeSpace[],
long getUsableSpace[],
java.io.File createTempFile[java.lang.String arg1, java.lang.String arg2, java.io.File arg3],
java.io.File createTempFile[java.lang.String arg1, java.lang.String arg2],
java.nio.file.Path toPath[],
void wait[long arg1],
void wait[long arg1, int arg2],
void wait[],
java.lang.Class getClass[],
void notify[],
void notifyAll[]]
</pre>
 
Line 217 ⟶ 349:
of each exported method.<br>
privateMethod is not exported because the first character is lowercase.
<langsyntaxhighlight lang="go">package main
 
import (
Line 253 ⟶ 385:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 273 ⟶ 405:
Sub func(image.Point, image.Point) image.Point func(image.Point) image.Point
</pre>
 
=={{Header|Insitux}}==
 
Insitux does not have classes and therefore technically does not have methods. However, it is possible to list all the functions in global lexical space:
 
<syntaxhighlight lang="insitux">
; lists all built-in and user-defined functions, including those within variables
(-> (symbols)
(map eval)
(filter (comp type-of (= "func"))))
 
; lists only user-defined functions, including those within variables
(-> (symbols)
(map eval)
(filter (comp type-of (= "func")))
(remove about))
</syntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang j>
NB. define a stack class
coclass 'Stack'
Line 317 ⟶ 466:
COCREATOR items
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.lang.reflect.Method;
 
public class ListMethods {
Line 344 ⟶ 493:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 368 ⟶ 517:
In JavaScript, methods are properties that are functions, so methods are retrieved by [[Reflection/List properties|getting properties]] and filtering. There are multiple ways of getting property names, each of which include different subsets of an object's properties, such as enumerable or inherited properties.
 
<langsyntaxhighlight lang="javascript">// Sample classes for reflection
function Super(name) {
this.name = name;
Line 452 ⟶ 601:
Object.entries(sub)
.filter(function(p) {return typeof p[1] == 'function';})
//[["subOwn", function () {...}]]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">methods(methods)
methods(println)</langsyntaxhighlight>
 
{{out}}
Line 474 ⟶ 623:
=={{header|Kotlin}}==
Note that kotlin-reflect.jar needs to be included in the classpath for this program.
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
import kotlin.reflect.full.functions
Line 497 ⟶ 646:
val fs = c.functions
for (f in fs) println("${f.name}, ${f.visibility}")
}</langsyntaxhighlight>
 
{{out}}
Line 514 ⟶ 663:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- parent script "MyClass"
 
on foo (me)
Line 522 ⟶ 671:
on bar (me)
put "bar"
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
put obj.handlers()
-- [#foo, #bar]
Line 534 ⟶ 683:
 
call(#bar, obj)
-- "bar"</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function helloWorld()
print "Hello World"
end
Line 557 ⟶ 706:
end
 
printFunctions(_G)</langsyntaxhighlight>
{{out}}
<pre>assert
Line 592 ⟶ 741:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// create a class with methods that will be listed
class Methods
def static method1()
Line 611 ⟶ 760:
for method in dir(new(Methods))
println method
end</langsyntaxhighlight>
 
{{out}}
Line 648 ⟶ 797:
=={{header|Nim}}==
Nim separates data and functions, but with method call syntax, any function that has that object as its first parameter can be used like a method:
<langsyntaxhighlight lang="nim">type Foo = object
proc bar(f:Foo) = echo "bar"
var f:Foo
f.bar()</langsyntaxhighlight>
this also means object 'methods' can be defined across multiple source files
 
Line 661 ⟶ 810:
and
* have our type, or a related type (var Foo, ptr Foo, ref Foo) as first parameter
<langsyntaxhighlight lang="nim">import macros, fusion/matching
{.experimental: "caseStmtMacros".}
macro listMethods(modulepath:static string, typename): untyped =
Line 704 ⟶ 853:
#works for any module:
#const lib = "/path/to/nim/lib/pure/collections/tables.nim"
echo listMethods(lib,Table[A,B])</langsyntaxhighlight>
{{out}}<pre>@["a", "b", "c", "d", "e"]
@["[]=", "[]", "[]", "hasKey", "contains", "hasKeyOrPut", "getOrDefault", "getOrDefault", "mgetOrPut", "len", "add", "del", "pop", "take", "clear", "$", "withValue", "withValue", "pairs", "mpairs", "keys", "values", "mvalues", "allValues"]</pre>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
Line 731 ⟶ 880:
free(methods);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 741 ⟶ 890:
Note that the overloaded comparison operator also shows up in the list of methods.
 
<langsyntaxhighlight lang="perl">package Nums;
 
use overload ('<=>' => \&compare);
Line 750 ⟶ 899:
 
my $a = Nums->new(42);
print "$_\n" for %{ref ($a)."::" });</langsyntaxhighlight>
{{out}}
<pre>double
Line 761 ⟶ 910:
 
Another alternative is the module <code>Class::MOP</code>, which implements a meta-object protocol for the Perl. It alters nothing about Perl's object system; it is just a tool for manipulation and introspection. Note that this output includes methods inherited methods (<tt>DOES, VERSION, can, isa</tt>)
<langsyntaxhighlight lang="perl">use Class::MOP;
my $meta = Class::MOP::Class->initialize( ref $a );
say join "\n", $meta->get_all_method_names()</langsyntaxhighlight>
{{out}}
<pre>compare
Line 778 ⟶ 927:
===emulated===
Even before the introduction of classes (see below), but this sort of thing was fairly easy to emulate.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">METHODS</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">PROPERTIES</span>
Line 816 ⟶ 965:
<span style="color: #0000FF;">?</span><span style="color: #000000;">get_all_methods</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 825 ⟶ 974:
Needs 0.8.1+
Note that content from and parameters to get_struct_fields() may change between releases.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">class</span> <span style="color: #000000;">c</span>
<span style="color: #008080;">private</span> <span style="color: #008080;">function</span> <span style="color: #000000;">foo</span><span style="color: #0000FF;">();</span>
Line 840 ⟶ 989:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 848 ⟶ 997:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?
class Foo {
function bar(int $x) {
Line 860 ⟶ 1,009:
echo $method_info;
}
?></langsyntaxhighlight>
{{out}}
<pre>
Line 879 ⟶ 1,028:
First we define a rectangle class <code>+Rectangle</code> as subclass of a shape class <code>+Shape</code>:
 
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
# The Rectangle class
(class +Rectangle +Shape)
Line 897 ⟶ 1,046:
(dm draw> ()
(drawRect (: x) (: y) (: dx) (: dy)) ) # Hypothetical function 'drawRect'
</syntaxhighlight>
</lang>
 
Then we can create an object of the +Rectangle class and check its methods using the <code>method</code> function.
 
<syntaxhighlight lang="text">
: (setq R (new '(+Rectangle) 0 0 30 20))
-> $177356065126400
Line 907 ⟶ 1,056:
: (methods R)
-> ((draw> . +Rectangle) (perimeter> . +Rectangle) (area> . +Rectangle) (T . +Rectangle) (move> . +Shape))
</syntaxhighlight>
</lang>
 
 
Line 915 ⟶ 1,064:
In Python, methods are properties that are functions, so methods are retrieved by [[Reflection/List properties|getting properties]] and filtering, using (e.g.) <code>[https://docs.python.org/3.5/library/functions.html#dir dir()]</code> and a list comprehension. Python's <code>[https://docs.python.org/3.5/library/inspect.html#module-inspect inspect]</code> module offers a simple way to get a list of an object's methods, though it won't include wrapped, C-native methods (type 'method-wrapper', type 'wrapper_descriptor', or class 'wrapper_descriptor', depending on version). Dynamic methods can be listed by overriding <code>[https://docs.python.org/3/reference/datamodel.html#object.__dir__ __dir__]</code> in the class.
 
<langsyntaxhighlight lang="python">import inspect
 
# Sample classes for inspection
Line 1,007 ⟶ 1,156:
# names using inspect
map(lambda t: t[0], inspect.getmembers(sub, predicate=inspect.ismethod))
#['__dir__', '__getattr__', '__init__', '__str__', 'cls', 'doSub', 'doSup', 'otherMethod', 'strs', 'subCls', 'supCls']</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 1,015 ⟶ 1,164:
Each is represented as a <tt>Method</tt> object that contains a bunch of info:
 
<syntaxhighlight lang="raku" perl6line>class Foo {
method foo ($x) { }
method bar ($x, $y) { }
Line 1,025 ⟶ 1,174:
for $object.^methods {
say join ", ", .name, .arity, .count, .signature.gist
}</langsyntaxhighlight>
 
{{out}}
Line 1,035 ⟶ 1,184:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Reflection/List methods
 
Line 1,053 ⟶ 1,202:
func f4
see "hello from f4" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,072 ⟶ 1,221:
Dynamic methods can be listed by overriding these methods. Ancestor methods can be filtered out by subtracting a list of methods from the ancestor.
 
<langsyntaxhighlight lang="ruby"># Sample classes for reflection
class Super
CLASSNAME = 'super'
Line 1,203 ⟶ 1,352:
#=> [:superOwn, :subOwn, :incr]
p sub.singleton_methods
#=> [:superOwn, :subOwn]</langsyntaxhighlight>
 
=={{header|Scala}}==
===Java Interoperability===
{{Out}}Best seen running in your browser by [https://scastie.scala-lang.org/5mLHFfBeQCuGpc9Q7PXxgw Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">object ListMethods extends App {
 
private val obj = new {
Line 1,223 ⟶ 1,372:
clazz.getDeclaredMethods.foreach(m => println(s"${m}}"))
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
The super-method ''Object.methods()'' returns an Hash with method names as keys and ''LazyMethod'' objects as values. Each ''LazyMethod'' can be called with zero or more arguments, internally invoking the method on the object on which ''.methods'' was called.
<langsyntaxhighlight lang="ruby">class Example {
method foo { }
method bar(arg) { say "bar(#{arg})" }
Line 1,236 ⟶ 1,385:
 
var meth = obj.methods.item(:bar) # `LazyMethod` representation for `obj.bar()`
meth(123) # calls obj.bar()</langsyntaxhighlight>
 
=={{header|Tcl}}==
In TclOO, the <tt>info</tt> command can inspect the complete state of an object or a class, including private and methods:
 
<langsyntaxhighlight Tcllang="tcl">% info object methods ::oo::class -all -private
<cloned> create createWithNamespace destroy eval new unknown variable varname</langsyntaxhighlight>
 
For <i>many</i> more examples, see https://wiki.tcl.tk/40640 and the linked manuals for <tt>info class</tt> and <tt>info object</tt>. Plugins for <b>tkcon</b> and <b>twDebugInspector</b> (also found on the wiki) use this to create interactive object inspectors similar to [[Smalltalk]]'s.
Line 1,250 ⟶ 1,399:
 
Note that, since attributes are stored internally as a map, the order in which the method names appear is undefined.
<langsyntaxhighlight ecmascriptlang="wren">#! instance_methods(m, n, o)
#! instance_properties(p, q, r)
class C {
Line 1,270 ⟶ 1,419:
var c = C.new() // create an object of type C
System.print("List of instance methods available for object 'c':")
for (method in c.type.attributes.self["instance_methods"]) System.print(method.key)</langsyntaxhighlight>
 
{{out}}
Line 1,282 ⟶ 1,431:
=={{header|zkl}}==
Every object has a "methods" method, which returns a list of method names [for that object]. If you want to get a method from a string, you can use reflection.
<langsyntaxhighlight lang="zkl">methods:=List.methods;
methods.println();
List.method(methods[0]).println(); // == .Method(name) == .BaseClass(name) </langsyntaxhighlight>
{{out}}
<pre>
162

edits