Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
6
Task/Reflection-List-methods/00-META.yaml
Normal file
6
Task/Reflection-List-methods/00-META.yaml
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
category:
|
||||
- Programming Tasks
|
||||
- Object oriented
|
||||
from: http://rosettacode.org/wiki/Reflection/List_methods
|
||||
note: Reflection
|
||||
5
Task/Reflection-List-methods/00-TASK.txt
Normal file
5
Task/Reflection-List-methods/00-TASK.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
;Task:
|
||||
The goal is to get the methods of an object, as names, values or both.
|
||||
|
||||
Some languages offer [[Respond to an unknown method call|dynamic methods]], which in general can only be inspected if a class' public API includes a way of listing them.
|
||||
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
using System;
|
||||
using System.Reflection;
|
||||
|
||||
public class Rosetta
|
||||
{
|
||||
public static void Main()
|
||||
{
|
||||
//Let's get all methods, not just public ones.
|
||||
BindingFlags flags = BindingFlags.Instance | BindingFlags.Static
|
||||
| BindingFlags.Public | BindingFlags.NonPublic
|
||||
| BindingFlags.DeclaredOnly;
|
||||
|
||||
foreach (var method in typeof(TestForMethodReflection).GetMethods(flags))
|
||||
Console.WriteLine(method);
|
||||
}
|
||||
|
||||
class TestForMethodReflection
|
||||
{
|
||||
public void MyPublicMethod() {}
|
||||
private void MyPrivateMethod() {}
|
||||
|
||||
public static void MyPublicStaticMethod() {}
|
||||
private static void MyPrivateStaticMethod() {}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
; Including listing private methods in the clojure.set namespace:
|
||||
=> (keys (ns-interns 'clojure.set))
|
||||
(union map-invert join select intersection superset? index bubble-max-key subset? rename rename-keys project difference)
|
||||
|
||||
; Only public:
|
||||
=> (keys (ns-publics 'clojure.set))
|
||||
(union map-invert join select intersection superset? index subset? rename rename-keys project difference)
|
||||
33
Task/Reflection-List-methods/D/reflection-list-methods.d
Normal file
33
Task/Reflection-List-methods/D/reflection-list-methods.d
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
struct S {
|
||||
bool b;
|
||||
|
||||
void foo() {}
|
||||
private void bar() {}
|
||||
}
|
||||
|
||||
class C {
|
||||
bool b;
|
||||
|
||||
void foo() {}
|
||||
private void bar() {}
|
||||
}
|
||||
|
||||
void printMethods(T)() if (is(T == class) || is(T == struct)) {
|
||||
import std.stdio;
|
||||
import std.traits;
|
||||
|
||||
writeln("Methods of ", T.stringof, ":");
|
||||
foreach (m; __traits(allMembers, T)) {
|
||||
static if (__traits(compiles, (typeof(__traits(getMember, T, m))))) {
|
||||
alias typeof(__traits(getMember, T, m)) ti;
|
||||
static if (isFunction!ti) {
|
||||
writeln(" ", m);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
printMethods!S;
|
||||
printMethods!C;
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import system'routines;
|
||||
import system'dynamic;
|
||||
import extensions;
|
||||
|
||||
class MyClass
|
||||
{
|
||||
myMethod1() {}
|
||||
|
||||
myMethod2(x) {}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
var o := new MyClass();
|
||||
|
||||
o.__getClass().__getMessages().forEach:(p)
|
||||
{
|
||||
console.printLine("o.",p)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
USING: io math prettyprint see ;
|
||||
|
||||
"The list of methods contained in the generic word + :" print
|
||||
\ + methods . nl
|
||||
|
||||
"The list of methods specializing on the fixnum class:" print
|
||||
fixnum methods .
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
a = new array
|
||||
methods[a]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
f = newJava["java.io.File", "."]
|
||||
methods[f]
|
||||
37
Task/Reflection-List-methods/Go/reflection-list-methods.go
Normal file
37
Task/Reflection-List-methods/Go/reflection-list-methods.go
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type t int // A type definition
|
||||
|
||||
// Some methods on the type
|
||||
func (r t) Twice() t { return r * 2 }
|
||||
func (r t) Half() t { return r / 2 }
|
||||
func (r t) Less(r2 t) bool { return r < r2 }
|
||||
func (r t) privateMethod() {}
|
||||
|
||||
func main() {
|
||||
report(t(0))
|
||||
report(image.Point{})
|
||||
}
|
||||
|
||||
func report(x interface{}) {
|
||||
v := reflect.ValueOf(x)
|
||||
t := reflect.TypeOf(x) // or v.Type()
|
||||
n := t.NumMethod()
|
||||
fmt.Printf("Type %v has %d exported methods:\n", t, n)
|
||||
const format = "%-6s %-46s %s\n"
|
||||
fmt.Printf(format, "Name", "Method expression", "Method value")
|
||||
for i := 0; i < n; i++ {
|
||||
fmt.Printf(format,
|
||||
t.Method(i).Name,
|
||||
t.Method(i).Func.Type(),
|
||||
v.Method(i).Type(),
|
||||
)
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
40
Task/Reflection-List-methods/J/reflection-list-methods.j
Normal file
40
Task/Reflection-List-methods/J/reflection-list-methods.j
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
NB. define a stack class
|
||||
coclass 'Stack'
|
||||
create =: 3 : 'items =: i. 0'
|
||||
push =: 3 : '# items =: items , < y'
|
||||
top =: 3 : '> {: items'
|
||||
pop =: 3 : ([;._2' a =. top 0; items =: }: items; a;')
|
||||
destroy =: codestroy
|
||||
cocurrent 'base'
|
||||
|
||||
names_Stack_'' NB. all names
|
||||
create destroy pop push top
|
||||
|
||||
'p' names_Stack_ 3 NB. verbs that start with p
|
||||
pop push
|
||||
|
||||
|
||||
NB. make an object. The dyadic definition of cownew invokes the create verb
|
||||
S =: conew~ 'Stack'
|
||||
|
||||
names__S'' NB. object specific names
|
||||
COCREATOR items
|
||||
|
||||
|
||||
pop__S NB. introspection: get the verbs definition
|
||||
3 : 0
|
||||
a =. top 0
|
||||
items =: }: items
|
||||
a
|
||||
)
|
||||
|
||||
|
||||
NB. get the search path of object S
|
||||
copath S
|
||||
┌─────┬─┐
|
||||
│Stack│z│
|
||||
└─────┴─┘
|
||||
|
||||
|
||||
names__S 0 NB. get the object specific data
|
||||
COCREATOR items
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
import java.lang.reflect.Method;
|
||||
|
||||
public class ListMethods {
|
||||
public int examplePublicInstanceMethod(char c, double d) {
|
||||
return 42;
|
||||
}
|
||||
|
||||
private boolean examplePrivateInstanceMethod(String s) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Class clazz = ListMethods.class;
|
||||
|
||||
System.out.println("All public methods (including inherited):");
|
||||
for (Method m : clazz.getMethods()) {
|
||||
System.out.println(m);
|
||||
}
|
||||
System.out.println();
|
||||
System.out.println("All declared methods (excluding inherited):");
|
||||
for (Method m : clazz.getDeclaredMethods()) {
|
||||
System.out.println(m);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
// Sample classes for reflection
|
||||
function Super(name) {
|
||||
this.name = name;
|
||||
this.superOwn = function() { return 'super owned'; };
|
||||
}
|
||||
Super.prototype = {
|
||||
constructor: Super
|
||||
className: 'super',
|
||||
toString: function() { return "Super(" + this.name + ")"; },
|
||||
doSup: function() { return 'did super stuff'; }
|
||||
}
|
||||
|
||||
function Sub() {
|
||||
Object.getPrototypeOf(this).constructor.apply(this, arguments);
|
||||
this.rest = [].slice.call(arguments, 1);
|
||||
this.subOwn = function() { return 'sub owned'; };
|
||||
}
|
||||
Sub.prototype = Object.assign(
|
||||
new Super('prototype'),
|
||||
{
|
||||
constructor: Sub
|
||||
className: 'sub',
|
||||
toString: function() { return "Sub(" + this.name + ")"; },
|
||||
doSub: function() { return 'did sub stuff'; }
|
||||
});
|
||||
|
||||
Object.defineProperty(Sub.prototype, 'shush', {
|
||||
value: function() { return ' non-enumerable'; },
|
||||
enumerable: false // the default
|
||||
});
|
||||
|
||||
var sup = new Super('sup'),
|
||||
sub = new Sub('sub', 0, 'I', 'two');
|
||||
|
||||
Object.defineProperty(sub, 'quiet', {
|
||||
value: function() { return 'sub owned non-enumerable'; },
|
||||
enumerable: false
|
||||
});
|
||||
|
||||
// get enumerable methods on an object and its ancestors
|
||||
function get_method_names(obj) {
|
||||
var methods = [];
|
||||
for (var p in obj) {
|
||||
if (typeof obj[p] == 'function') {
|
||||
methods.push(p);
|
||||
}
|
||||
}
|
||||
return methods;
|
||||
}
|
||||
|
||||
get_method_names(sub);
|
||||
//["subOwn", "superOwn", "toString", "doSub", "doSup"]
|
||||
|
||||
// get enumerable properties on an object and its ancestors
|
||||
function get_property_names(obj) {
|
||||
var properties = [];
|
||||
for (var p in obj) {
|
||||
properties.push(p);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
|
||||
// alternate way to get enumerable method names on an object and its ancestors
|
||||
function get_method_names(obj) {
|
||||
return get_property_names(obj)
|
||||
.filter(function(p) {return typeof obj[p] == 'function';});
|
||||
}
|
||||
|
||||
get_method_names(sub);
|
||||
//["subOwn", "superOwn", "toString", "doSub", "doSup"]
|
||||
|
||||
// get enumerable & non-enumerable method names set directly on an object
|
||||
Object.getOwnPropertyNames(sub)
|
||||
.filter(function(p) {return typeof sub[p] == 'function';})
|
||||
//["subOwn", "shhh"]
|
||||
|
||||
// get enumerable method names set directly on an object
|
||||
Object.keys(sub)
|
||||
.filter(function(p) {return typeof sub[p] == 'function';})
|
||||
//["subOwn"]
|
||||
|
||||
// get enumerable method names & values set directly on an object
|
||||
Object.entries(sub)
|
||||
.filter(function(p) {return typeof p[1] == 'function';})
|
||||
//[["subOwn", function () {...}]]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
methods(methods)
|
||||
methods(println)
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
// Version 1.2.31
|
||||
|
||||
import kotlin.reflect.full.functions
|
||||
|
||||
open class MySuperClass {
|
||||
fun mySuperClassMethod(){}
|
||||
}
|
||||
|
||||
open class MyClass : MySuperClass() {
|
||||
fun myPublicMethod(){}
|
||||
|
||||
internal fun myInternalMethod(){}
|
||||
|
||||
protected fun myProtectedMethod(){}
|
||||
|
||||
private fun myPrivateMethod(){}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val c = MyClass::class
|
||||
println("List of methods declared in ${c.simpleName} and its superclasses:\n")
|
||||
val fs = c.functions
|
||||
for (f in fs) println("${f.name}, ${f.visibility}")
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
-- parent script "MyClass"
|
||||
|
||||
on foo (me)
|
||||
put "foo"
|
||||
end
|
||||
|
||||
on bar (me)
|
||||
put "bar"
|
||||
end
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
obj = script("MyClass").new()
|
||||
put obj.handlers()
|
||||
-- [#foo, #bar]
|
||||
|
||||
-- The returned list contains the object's methods ("handlers") as "symbols".
|
||||
-- Those can be used like this to call the corresponding method:
|
||||
call(#foo, obj)
|
||||
-- "foo"
|
||||
|
||||
call(#bar, obj)
|
||||
-- "bar"
|
||||
21
Task/Reflection-List-methods/Lua/reflection-list-methods.lua
Normal file
21
Task/Reflection-List-methods/Lua/reflection-list-methods.lua
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
function helloWorld()
|
||||
print "Hello World"
|
||||
end
|
||||
|
||||
-- Will list all functions in the given table, but does not recurse into nexted tables
|
||||
function printFunctions(t)
|
||||
local s={}
|
||||
local n=0
|
||||
for k in pairs(t) do
|
||||
n=n+1 s[n]=k
|
||||
end
|
||||
table.sort(s)
|
||||
for k,v in ipairs(s) do
|
||||
f = t[v]
|
||||
if type(f) == "function" then
|
||||
print(v)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
printFunctions(_G)
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
// create a class with methods that will be listed
|
||||
class Methods
|
||||
def static method1()
|
||||
return "this is a static method. it will not be printed"
|
||||
end
|
||||
def method2()
|
||||
return "this is not a static method"
|
||||
end
|
||||
|
||||
def operator=(other)
|
||||
// operator methods are listed by both their defined name and
|
||||
// by their internal name, which in this case is isEqual
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
// lists all nanoquery and java native methods
|
||||
for method in dir(new(Methods))
|
||||
println method
|
||||
end
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
type Foo = object
|
||||
proc bar(f:Foo) = echo "bar"
|
||||
var f:Foo
|
||||
f.bar()
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
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])
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
@interface Foo : NSObject
|
||||
@end
|
||||
@implementation Foo
|
||||
- (int)bar:(double)x {
|
||||
return 42;
|
||||
}
|
||||
@end
|
||||
|
||||
int main() {
|
||||
unsigned int methodCount;
|
||||
Method *methods = class_copyMethodList([Foo class], &methodCount);
|
||||
for (unsigned int i = 0; i < methodCount; i++) {
|
||||
Method m = methods[i];
|
||||
SEL selector = method_getName(m);
|
||||
const char *typeEncoding = method_getTypeEncoding(m);
|
||||
NSLog(@"%@\t%s", NSStringFromSelector(selector), typeEncoding);
|
||||
}
|
||||
free(methods);
|
||||
return 0;
|
||||
}
|
||||
13
Task/Reflection-List-methods/PHP/reflection-list-methods.php
Normal file
13
Task/Reflection-List-methods/PHP/reflection-list-methods.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?
|
||||
class Foo {
|
||||
function bar(int $x) {
|
||||
}
|
||||
}
|
||||
|
||||
$method_names = get_class_methods('Foo');
|
||||
foreach ($method_names as $name) {
|
||||
echo "$name\n";
|
||||
$method_info = new ReflectionMethod('Foo', $name);
|
||||
echo $method_info;
|
||||
}
|
||||
?>
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package Nums;
|
||||
|
||||
use overload ('<=>' => \&compare);
|
||||
sub new { my $self = shift; bless [@_] }
|
||||
sub flip { my @a = @_; 1/$a }
|
||||
sub double { my @a = @_; 2*$a }
|
||||
sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) }
|
||||
|
||||
my $a = Nums->new(42);
|
||||
print "$_\n" for %{ref ($a)."::" });
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
use Class::MOP;
|
||||
my $meta = Class::MOP::Class->initialize( ref $a );
|
||||
say join "\n", $meta->get_all_method_names()
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
-->
|
||||
<span style="color: #008080;">enum</span> <span style="color: #000000;">METHODS</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">PROPERTIES</span>
|
||||
|
||||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">all_methods</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<span style="color: #000000;">all_methods</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
|
||||
<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>
|
||||
<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>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
-->
|
||||
<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>
|
||||
<span style="color: #008080;">public</span> <span style="color: #008080;">procedure</span> <span style="color: #000000;">bar</span><span style="color: #0000FF;">();</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">class</span>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# 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'
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
: (setq R (new '(+Rectangle) 0 0 30 20))
|
||||
-> $177356065126400
|
||||
|
||||
: (methods R)
|
||||
-> ((draw> . +Rectangle) (perimeter> . +Rectangle) (area> . +Rectangle) (T . +Rectangle) (move> . +Shape))
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
import inspect
|
||||
|
||||
# Sample classes for inspection
|
||||
class Super(object):
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
|
||||
def __str__(self):
|
||||
return "Super(%s)" % (self.name,)
|
||||
|
||||
def doSup(self):
|
||||
return 'did super stuff'
|
||||
|
||||
@classmethod
|
||||
def cls(cls):
|
||||
return 'cls method (in sup)'
|
||||
|
||||
@classmethod
|
||||
def supCls(cls):
|
||||
return 'Super method'
|
||||
|
||||
@staticmethod
|
||||
def supStatic():
|
||||
return 'static method'
|
||||
|
||||
class Other(object):
|
||||
def otherMethod(self):
|
||||
return 'other method'
|
||||
|
||||
class Sub(Other, Super):
|
||||
def __init__(self, name, *args):
|
||||
super(Sub, self).__init__(name);
|
||||
self.rest = args;
|
||||
self.methods = {}
|
||||
|
||||
def __dir__(self):
|
||||
return list(set( \
|
||||
sum([dir(base) for base in type(self).__bases__], []) \
|
||||
+ type(self).__dict__.keys() \
|
||||
+ self.__dict__.keys() \
|
||||
+ self.methods.keys() \
|
||||
))
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name in self.methods:
|
||||
if callable(self.methods[name]) and self.methods[name].__code__.co_argcount > 0:
|
||||
if self.methods[name].__code__.co_varnames[0] == 'self':
|
||||
return self.methods[name].__get__(self, type(self))
|
||||
if self.methods[name].__code__.co_varnames[0] == 'cls':
|
||||
return self.methods[name].__get__(type(self), type)
|
||||
return self.methods[name]
|
||||
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
|
||||
|
||||
def __str__(self):
|
||||
return "Sub(%s)" % self.name
|
||||
|
||||
def doSub():
|
||||
return 'did sub stuff'
|
||||
|
||||
@classmethod
|
||||
def cls(cls):
|
||||
return 'cls method (in Sub)'
|
||||
|
||||
@classmethod
|
||||
def subCls(cls):
|
||||
return 'Sub method'
|
||||
|
||||
@staticmethod
|
||||
def subStatic():
|
||||
return 'Sub method'
|
||||
|
||||
sup = Super('sup')
|
||||
sub = Sub('sub', 0, 'I', 'two')
|
||||
sub.methods['incr'] = lambda x: x+1
|
||||
sub.methods['strs'] = lambda self, x: str(self) * x
|
||||
|
||||
# names
|
||||
[method for method in dir(sub) if callable(getattr(sub, method))]
|
||||
# instance methods
|
||||
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == sub]
|
||||
#['__dir__', '__getattr__', '__init__', '__str__', 'doSub', 'doSup', 'otherMethod', 'strs']
|
||||
# class methods
|
||||
[method for method in dir(sub) if callable(getattr(sub, method)) and hasattr(getattr(sub, method), '__self__') and getattr(sub, method).__self__ == type(sub)]
|
||||
#['__subclasshook__', 'cls', 'subCls', 'supCls']
|
||||
# static & free dynamic methods
|
||||
[method for method in dir(sub) if callable(getattr(sub, method)) and type(getattr(sub, method)) == type(lambda:nil)]
|
||||
#['incr', 'subStatic', 'supStatic']
|
||||
|
||||
# names & values; doesn't include wrapped, C-native methods
|
||||
inspect.getmembers(sub, predicate=inspect.ismethod)
|
||||
# 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']
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# Project : Reflection/List methods
|
||||
|
||||
o1 = new test
|
||||
aList = methods(o1)
|
||||
for x in aList
|
||||
cCode = "o1."+x+"()"
|
||||
eval(cCode)
|
||||
next
|
||||
Class Test
|
||||
func f1
|
||||
see "hello from f1" + nl
|
||||
func f2
|
||||
see "hello from f2" + nl
|
||||
func f3
|
||||
see "hello from f3" + nl
|
||||
func f4
|
||||
see "hello from f4" + nl
|
||||
132
Task/Reflection-List-methods/Ruby/reflection-list-methods.rb
Normal file
132
Task/Reflection-List-methods/Ruby/reflection-list-methods.rb
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
# Sample classes for reflection
|
||||
class Super
|
||||
CLASSNAME = 'super'
|
||||
|
||||
def initialize(name)
|
||||
@name = name
|
||||
def self.superOwn
|
||||
'super owned'
|
||||
end
|
||||
end
|
||||
|
||||
def to_s
|
||||
"Super(#{@name})"
|
||||
end
|
||||
|
||||
def doSup
|
||||
'did super stuff'
|
||||
end
|
||||
|
||||
def self.superClassStuff
|
||||
'did super class stuff'
|
||||
end
|
||||
|
||||
protected
|
||||
def protSup
|
||||
"Super's protected"
|
||||
end
|
||||
|
||||
private
|
||||
def privSup
|
||||
"Super's private"
|
||||
end
|
||||
end
|
||||
|
||||
module Other
|
||||
def otherStuff
|
||||
'did other stuff'
|
||||
end
|
||||
end
|
||||
|
||||
class Sub < Super
|
||||
CLASSNAME = 'sub'
|
||||
attr_reader :dynamic
|
||||
|
||||
include Other
|
||||
|
||||
def initialize(name, *args)
|
||||
super(name)
|
||||
@rest = args;
|
||||
@dynamic = {}
|
||||
def self.subOwn
|
||||
'sub owned'
|
||||
end
|
||||
end
|
||||
|
||||
def methods(regular=true)
|
||||
super + @dynamic.keys
|
||||
end
|
||||
|
||||
def method_missing(name, *args, &block)
|
||||
return super unless @dynamic.member?(name)
|
||||
method = @dynamic[name]
|
||||
if method.arity > 0
|
||||
if method.parameters[0][1] == :self
|
||||
args.unshift(self)
|
||||
end
|
||||
if method.lambda?
|
||||
# procs (hence methods) set missing arguments to `nil`, lambdas don't, so extend args explicitly
|
||||
args += args + [nil] * [method.arity - args.length, 0].max
|
||||
# procs (hence methods) discard extra arguments, lambdas don't, so discard arguments explicitly (unless lambda is variadic)
|
||||
if method.parameters[-1][0] != :rest
|
||||
args = args[0,method.arity]
|
||||
end
|
||||
end
|
||||
method.call(*args)
|
||||
else
|
||||
method.call
|
||||
end
|
||||
end
|
||||
|
||||
def public_methods(all=true)
|
||||
super + @dynamic.keys
|
||||
end
|
||||
|
||||
def respond_to?(symbol, include_all=false)
|
||||
@dynamic.member?(symbol) || super
|
||||
end
|
||||
|
||||
def to_s
|
||||
"Sub(#{@name})"
|
||||
end
|
||||
|
||||
def doSub
|
||||
'did sub stuff'
|
||||
end
|
||||
|
||||
def self.subClassStuff
|
||||
'did sub class stuff'
|
||||
end
|
||||
|
||||
protected
|
||||
def protSub
|
||||
"Sub's protected"
|
||||
end
|
||||
|
||||
private
|
||||
def privSub
|
||||
"Sub's private"
|
||||
end
|
||||
end
|
||||
|
||||
sup = Super.new('sup')
|
||||
sub = Sub.new('sub', 0, 'I', 'two')
|
||||
sub.dynamic[:incr] = proc {|i| i+1}
|
||||
|
||||
p sub.public_methods(false)
|
||||
#=> [:superOwn, :subOwn, :respond_to?, :method_missing, :to_s, :methods, :public_methods, :dynamic, :doSub, :incr]
|
||||
|
||||
p sub.methods - Object.methods
|
||||
#=> [:superOwn, :subOwn, :method_missing, :dynamic, :doSub, :protSub, :otherStuff, :doSup, :protSup, :incr]
|
||||
|
||||
p sub.public_methods - Object.public_methods
|
||||
#=> [:superOwn, :subOwn, :method_missing, :dynamic, :doSub, :otherStuff, :doSup, :incr]
|
||||
|
||||
p sub.methods - sup.methods
|
||||
#=> [:subOwn, :method_missing, :dynamic, :doSub, :protSub, :otherStuff, :incr]
|
||||
|
||||
# singleton/eigenclass methods
|
||||
p sub.methods(false)
|
||||
#=> [:superOwn, :subOwn, :incr]
|
||||
p sub.singleton_methods
|
||||
#=> [:superOwn, :subOwn]
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
object ListMethods extends App {
|
||||
|
||||
private val obj = new {
|
||||
def examplePublicInstanceMethod(c: Char, d: Double) = 42
|
||||
|
||||
private def examplePrivateInstanceMethod(s: String) = true
|
||||
}
|
||||
private val clazz = obj.getClass
|
||||
|
||||
println("All public methods (including inherited):")
|
||||
clazz.getMethods.foreach(m => println(s"${m}"))
|
||||
|
||||
println("\nAll declared fields (excluding inherited):")
|
||||
clazz.getDeclaredMethods.foreach(m => println(s"${m}}"))
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
class Example {
|
||||
method foo { }
|
||||
method bar(arg) { say "bar(#{arg})" }
|
||||
}
|
||||
|
||||
var obj = Example()
|
||||
say obj.methods.keys.sort #=> ["bar", "call", "foo", "new"]
|
||||
|
||||
var meth = obj.methods.item(:bar) # `LazyMethod` representation for `obj.bar()`
|
||||
meth(123) # calls obj.bar()
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
% info object methods ::oo::class -all -private
|
||||
<cloned> create createWithNamespace destroy eval new unknown variable varname
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
#! 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)
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
methods:=List.methods;
|
||||
methods.println();
|
||||
List.method(methods[0]).println(); // == .Method(name) == .BaseClass(name)
|
||||
Loading…
Add table
Add a link
Reference in a new issue