Reflection/List methods: Difference between revisions

Add Ecstasy example
(Add Ecstasy example)
 
(21 intermediate revisions by 11 users not shown)
Line 1:
{{draft task|Reflection}}
{{omit from|C}}
{{omit from|C++}}
{{omit from|Modula-2}}
{{omit from|Rust}}
{{omit from|6502 Assembly}}
{{omit from|68000 Assembly}}
{{omit from|Z80 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|x86 Assembly}}
{{omit from|ARM Assembly}}
[[Category:Programming Tasks]] [[Category:Object oriented]]
 
Line 12 ⟶ 18:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Reflection;
 
Line 37 ⟶ 43:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 55 ⟶ 61:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">
; Including listing private methods in the clojure.set namespace:
=> (keys (ns-interns 'clojure.set))
Line 62 ⟶ 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 98 ⟶ 104:
printMethods!S;
printMethods!C;
}</langsyntaxhighlight>
 
{{out}}
Line 112 ⟶ 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 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'dynamic;
import extensions;
Line 130 ⟶ 164:
var o := new MyClass();
o.__getClass().__getMessages().forEach::(p)
{
console.printLine("o.",p)
}
}</langsyntaxhighlight>
{{out}}
<pre>
o.equal[12]
o.notequal[12]
o.myMethod1toPrintable[01]
o.myMethod2myMethod1[1]
o.myMethod2[12]
o.#cast[0]
</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 153 ⟶ 186:
 
"The list of methods specializing on the fixnum class:" print
fixnum methods .</langsyntaxhighlight>
{{out}}
<pre>
Line 203 ⟶ 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 211 ⟶ 349:
of each exported method.<br>
privateMethod is not exported because the first character is lowercase.
<langsyntaxhighlight lang="go">package main
 
import (
Line 247 ⟶ 385:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 267 ⟶ 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 311 ⟶ 466:
COCREATOR items
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.lang.reflect.Method;
 
public class ListMethods {
Line 338 ⟶ 493:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 362 ⟶ 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 446 ⟶ 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 468 ⟶ 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 491 ⟶ 646:
val fs = c.functions
for (f in fs) println("${f.name}, ${f.visibility}")
}</langsyntaxhighlight>
 
{{out}}
Line 508 ⟶ 663:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- parent script "MyClass"
 
on foo (me)
Line 516 ⟶ 671:
on bar (me)
put "bar"
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
put obj.handlers()
-- [#foo, #bar]
Line 528 ⟶ 683:
 
call(#bar, obj)
-- "bar"</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function helloWorld()
print "Hello World"
end
Line 551 ⟶ 706:
end
 
printFunctions(_G)</langsyntaxhighlight>
{{out}}
<pre>assert
Line 586 ⟶ 741:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// create a class with methods that will be listed
class Methods
def static method1()
Line 605 ⟶ 760:
for method in dir(new(Methods))
println method
end</langsyntaxhighlight>
 
{{out}}
Line 640 ⟶ 795:
method2
operator=</pre>
=={{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:
<syntaxhighlight lang="nim">type Foo = object
proc bar(f:Foo) = echo "bar"
var f:Foo
f.bar()</syntaxhighlight>
this also means object 'methods' can be defined across multiple source files
 
It's possible to inspect a module's entire AST at compile time with a macro,
here we are interested in
* any method-like definitions (funcs,procs,iterators,methods,macros,templates,etc)
that are
* exported (publicly useable)
and
* have our type, or a related type (var Foo, ptr Foo, ref Foo) as first parameter
<syntaxhighlight lang="nim">import macros, fusion/matching
{.experimental: "caseStmtMacros".}
macro listMethods(modulepath:static string, typename): untyped =
let module = parseStmt(staticRead(modulepath))
var procs: seq[string]
for stmt in module:
case stmt
of (kind: in {nnkFuncDef,nnkProcDef..nnkIteratorDef}):#any kind of methody thing
case stmt
of [
PostFix[_, @name],#only exported procs
_,
_,
FormalParams[
_, #return type
IdentDefs[ #first parameter
_, #paramname
(typename | #Foo
VarTy[typename] | #var Foo
PtrTy[typename] | #ptr Foo
RefTy[typename]), #ref Foo
_],
.._], #other params
.._]: procs.add($name)
result = newLit(procs)
type Bar = object
proc a*(b: Bar) = discard
func b*(b: Bar, c: int): string = discard
template c*(b: var Bar, c: float) = discard
iterator d*(b: ptr Bar):int = discard
method e*(b:ref Bar) {.base.} = discard
proc second_param*(a: int, b: Bar) = discard #will not match
proc unexported(a: Bar) = discard #will not match
template thisfile:string =
instantiationInfo().filename
echo thisfile.listMethods(Bar)
#works for any module:
#const lib = "/path/to/nim/lib/pure/collections/tables.nim"
echo listMethods(lib,Table[A,B])</syntaxhighlight>
{{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 664 ⟶ 880:
free(methods);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 674 ⟶ 890:
Note that the overloaded comparison operator also shows up in the list of methods.
 
<langsyntaxhighlight lang="perl">package Nums;
 
use overload ('<=>' => \&compare);
Line 683 ⟶ 899:
 
my $a = Nums->new(42);
print "$_\n" for %{ref ($a)."::" });</langsyntaxhighlight>
{{out}}
<pre>double
Line 694 ⟶ 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 708 ⟶ 924:
DOES</pre>
 
=={{header|Perl 6Phix}}==
===emulated===
 
Even before the introduction of classes (see below), but this sort of thing was fairly easy to emulate.
You can get a list of an object's methods using <tt>.^methods</tt>, which is part of the [https://docs.perl6.org/type/Metamodel$COLON$COLONClassHOW Meta Object Protocol].<br>
<!--<syntaxhighlight lang="phix">-->
Each is represented as a <tt>Method</tt> object that contains a bunch of info:
<span style="color: #008080;">enum</span> <span style="color: #000000;">METHODS</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">PROPERTIES</span>
 
<lang perl6>class Foo {
<span style="color: #004080;">sequence</span> <span style="color: #000000;">all_methods</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
method foo ($x) { }
method bar ($x, $y) { }
<span style="color: #008080;">function</span> <span style="color: #000000;">method_visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000080;font-style:italic;">/*data*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*user_data*/</span><span style="color: #0000FF;">)</span>
method baz ($x, $y?) { }
<span style="color: #000000;">all_methods</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">all_methods</span><span style="color: #0000FF;">,</span><span style="color: #000000;">key</span><span style="color: #0000FF;">)</span>
}
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
my $object = Foo.new;
 
<span style="color: #008080;">function</span> <span style="color: #000000;">get_all_methods</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
for $object.^methods {
<span style="color: #000000;">all_methods</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
say join ", ", .name, .arity, .count, .signature.gist
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">method_visitor</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">o</span><span style="color: #0000FF;">[</span><span style="color: #000000;">METHODS</span><span style="color: #0000FF;">])</span>
}</lang>
<span style="color: #008080;">return</span> <span style="color: #000000;">all_methods</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">exists</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #008000;">"exists"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--class X: Xmethods emulates a vtable</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">Xmethods</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"exists"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">exists</span><span style="color: #0000FF;">}})</span>
<span style="color: #000080;font-style:italic;">--class X: destructor</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">destructor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">destroy_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">[</span><span style="color: #000000;">PROPERTIES</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000080;font-style:italic;">--class X: create new instances</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">newX</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">Xproperties</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"y"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">}})</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">delete_routine</span><span style="color: #0000FF;">({</span><span style="color: #000000;">Xmethods</span><span style="color: #0000FF;">,</span><span style="color: #000000;">Xproperties</span><span style="color: #0000FF;">},</span><span style="color: #000000;">destructor</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">newX</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"string"</span><span style="color: #0000FF;">)</span>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{"exists"}
foo, 2, 2, (Foo $: $x, *%_)
bar, 3, 3, (Foo $: $x, $y, *%_)
baz, 2, 3, (Foo $: $x, $y?, *%_)
</pre>
===classes===
 
=={{headerlibheader|Phix/Class}}==
Needs 0.8.1+
Phix is not object orientated, but this sort of thing is fairly easy to emulate.
Note that content from and parameters to get_struct_fields() may change between releases.
<lang Phix>enum METHODS, PROPERTIES
<!--<syntaxhighlight lang="phix">-->
 
<span style="color: #008080;">class</span> <span style="color: #000000;">c</span>
sequence all_methods = {}
<span style="color: #008080;">private</span> <span style="color: #008080;">function</span> <span style="color: #000000;">foo</span><span style="color: #0000FF;">();</span>
 
<span style="color: #008080;">public</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">bar</span><span style="color: #0000FF;">();</span>
function method_visitor(object key, object /*data*/, object /*user_data*/)
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
all_methods = append(all_methods,key)
return 1
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">structs</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #7060A8;">as</span> <span style="color: #000000;">structs</span>
end function
<span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">structs</span><span style="color: #0000FF;">:</span><span style="color: #000000;">get_struct_fields</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
function get_all_methods(object o)
<span style="color: #0000FF;">{</span><span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">flags</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
all_methods = {}
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">flags</span><span style="color: #0000FF;">,</span><span style="color: #000000;">SF_RTN</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
traverse_dict(routine_id("method_visitor"),0,o[METHODS])
<span style="color: #008080;">if</span> <span style="color: #000000;">tid</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">ST_INTEGER</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (sanity check)</span>
return all_methods
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s:%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">structs</span><span style="color: #0000FF;">:</span><span style="color: #000000;">get_field_flags</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)})</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
--class X: Xmethods emulates a vtable
<!--</syntaxhighlight>-->
constant Xmethods = new_dict()
 
function exists()
return "exists"
end function
 
setd("exists",routine_id("exists"),Xmethods)
 
--class X: destructor
procedure destructor(object o)
destroy_dict(o[PROPERTIES])
end procedure
constant r_destroy = routine_id("destructor")
 
--class X: create new instances
function newX(object x,y)
integer Xproperties = new_dict()
setd("x",x,Xproperties)
setd("y",y,Xproperties)
object res = delete_routine({Xmethods,Xproperties},r_destroy)
return res
end function
 
object x = newX(2,"string")
 
?get_all_methods(x)</lang>
{{out}}
<pre>
foo:SF_PRIVATE+SF_FUNC
{"exists"}
bar:SF_PROC
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?
class Foo {
function bar(int $x) {
Line 794 ⟶ 1,009:
echo $method_info;
}
?></langsyntaxhighlight>
{{out}}
<pre>
Line 806 ⟶ 1,021:
}
</pre>
 
 
=={{header|PicoLisp}}==
The function <code>methods</code> can be used to print all methods of an object (only in debug mode):
 
First we define a rectangle class <code>+Rectangle</code> as subclass of a shape class <code>+Shape</code>:
 
<syntaxhighlight lang="picolisp">
# The Rectangle class
(class +Rectangle +Shape)
# dx dy
 
(dm T (X Y DX DY)
(super X Y)
(=: dx DX)
(=: dy DY) )
 
(dm area> ()
(* (: dx) (: dy)) )
 
(dm perimeter> ()
(* 2 (+ (: dx) (: dy))) )
 
(dm draw> ()
(drawRect (: x) (: y) (: dx) (: dy)) ) # Hypothetical function 'drawRect'
</syntaxhighlight>
 
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
 
: (methods R)
-> ((draw> . +Rectangle) (perimeter> . +Rectangle) (area> . +Rectangle) (T . +Rectangle) (move> . +Shape))
</syntaxhighlight>
 
 
 
 
=={{header|Python}}==
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 902 ⟶ 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}}==
(formerly Perl 6)
 
You can get a list of an object's methods using <tt>.^methods</tt>, which is part of the [https://docs.raku.org/type/Metamodel$COLON$COLONClassHOW Meta Object Protocol].<br>
Each is represented as a <tt>Method</tt> object that contains a bunch of info:
 
<syntaxhighlight lang="raku" line>class Foo {
method foo ($x) { }
method bar ($x, $y) { }
method baz ($x, $y?) { }
}
 
my $object = Foo.new;
 
for $object.^methods {
say join ", ", .name, .arity, .count, .signature.gist
}</syntaxhighlight>
 
{{out}}
<pre>
foo, 2, 2, (Foo $: $x, *%_)
bar, 3, 3, (Foo $: $x, $y, *%_)
baz, 2, 3, (Foo $: $x, $y?, *%_)
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Reflection/List methods
 
Line 923 ⟶ 1,202:
func f4
see "hello from f4" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 942 ⟶ 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,073 ⟶ 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,093 ⟶ 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,106 ⟶ 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.
 
=={{header|Wren}}==
Wren doesn't currently have reflection as such but it's possible to identify a class's methods and list them at runtime by placing a suitable attribute on the class.
 
Note that, since attributes are stored internally as a map, the order in which the method names appear is undefined.
<syntaxhighlight lang="wren">#! instance_methods(m, n, o)
#! instance_properties(p, q, r)
class C {
construct new() {}
 
m() {}
 
n() {}
 
o() {}
 
p {}
 
q {}
r {}
}
 
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)</syntaxhighlight>
 
{{out}}
<pre>
List of instance methods available for object 'c':
n
m
o
</pre>
 
=={{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