Reflection/List properties: Difference between revisions

Add Ecstasy example
m (typing error in PicoLisp)
(Add Ecstasy example)
 
(6 intermediate revisions by 5 users not shown)
Line 12:
=={{header|C sharp}}==
{{works with|C sharp|7}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 45:
}
 
}</langsyntaxhighlight>
{{out}}
<pre>
Line 56:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
struct S {
Line 90:
printProperties!S;
printProperties!C;
}</langsyntaxhighlight>
{{out}}
<pre>Properties of S:
Line 96:
Properties of C:
b</pre>
 
=={{header|Ecstasy}}==
For any object, the type of that object provides access to its properties:
 
<syntaxhighlight lang="ecstasy">
module test {
void run() {
@Inject Console console;
Property[] properties = &this.actualType.properties;
console.print($"The properties of {this}: {properties}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
x$ xec test
The properties of test: [immutable Array<Class<Object, Object, Object, Struct>> classes, immutable Map<String, Class<Object, Object, Object, Struct>> classByName, String simpleName, String qualifiedName, Version version, immutable Map<String, Module> modulesByPath]
</langpre>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'dynamic;
import extensions;
Line 105 ⟶ 124:
class MyClass
{
prop int X : prop;
prop string Y : prop;
}
 
public program()
{
Line 117 ⟶ 136:
this Y := "String";
};
 
MyClass.__getProperties().forEach::(p)
{
console.printLine("o.",p,"=",cast MessageName(p).getPropertyValue(o))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 131 ⟶ 150:
=={{header|Factor}}==
Mirrors present an object's slots and slot values as an associative structure.
<langsyntaxhighlight lang="factor">USING: assocs kernel math mirrors prettyprint strings ;
 
TUPLE: foo
Line 140 ⟶ 159:
 
"apple" "banana" 200 <foo> <mirror>
[ >alist ] [ object-slots ] bi [ . ] bi@</langsyntaxhighlight>
{{out}}
<pre>
Line 175 ⟶ 194:
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">package main
 
import (
Line 208 ⟶ 227:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 224 ⟶ 243:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.lang.reflect.Field
 
@SuppressWarnings("unused")
Line 247 ⟶ 266:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>All public fields (including inherited):
Line 267 ⟶ 286:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.lang.reflect.Field;
 
public class ListFields {
Line 287 ⟶ 306:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 301 ⟶ 320:
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. Properties in JavaScript can be enumerable or non-enumerable; enumerable properties are accessable when looping over the object with <code>for</code>. <code>Object.getOwnPropertyNames()</code>.
 
<langsyntaxhighlight lang="javascript">var obj = Object.create({
name: 'proto',
proto: true,
Line 332 ⟶ 351:
Object.entries(obj);
//[["name", "obj"], ["obj", true], ["doStuff", function()]]
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 350 ⟶ 369:
 
'''Example'''
<syntaxhighlight lang="jq">
<lang jq>
# Use jq's built-ins to generate a (recursive) synopsis of .
def synopsis:
Line 363 ⟶ 382:
true, null, [1,2], {"a": {"b": 3, "c": 4}, "x": "Rosetta Code"}, now
| ("\n\(.) ::", synopsis)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 390 ⟶ 409:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">for obj in (Int, 1, 1:10, collect(1:10), now())
println("\nObject: $obj\nDescription:")
dump(obj)
end</langsyntaxhighlight>
 
{{out}}
Line 423 ⟶ 442:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1
 
import kotlin.reflect.full.memberProperties
Line 448 ⟶ 467:
println("${prop.name.padEnd(13)} -> ${prop.get(example)}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 462 ⟶ 481:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">obj = script("MyClass").new()
obj.foo = 23
obj.bar = 42
Line 472 ⟶ 491:
repeat with i = 1 to cnt
put obj.getPropAt(i)&" = "&obj[i]
end repeat</langsyntaxhighlight>
 
{{Out}}
Line 481 ⟶ 500:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">a = 1
b = 2.0
c = "hello world"
Line 498 ⟶ 517:
listProperties(_G)
print("Package properties")
listProperties(package)</langsyntaxhighlight>
{{out}}
<pre>Global properties
Line 524 ⟶ 543:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">// declare a class that has fields to be listed
class Fields
declare static field1 = "this is a static field. it will not be listed"
Line 535 ⟶ 554:
for fieldname in Fields.getFieldNames()
println fieldname
end</langsyntaxhighlight>
 
{{out}}
Line 542 ⟶ 561:
field4</pre>
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
Foo = object
a: float
Line 549 ⟶ 568:
let f = Foo(a: 0.9, b: "hi", c: @[1,2,3])
for n, v in f.fieldPairs:
echo n, ": ", v</langsyntaxhighlight>
{{out}}
<pre>a: 0.9
Line 556 ⟶ 575:
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
Line 611 ⟶ 630:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 629 ⟶ 648:
 
Many of these options are also supported by other REXX implementations.
<langsyntaxhighlight lang="oorexx">/* REXX demonstrate uses of datatype() */
/* test values */
d.1=''
Line 673 ⟶ 692:
Say ol
End
Say hdr</langsyntaxhighlight>
{{out}}
<pre> A B I L M N O S U V W X 9 datatype(v)
Line 693 ⟶ 712:
=={{header|Perl}}==
In Perl's bare-bones native OO system, an object is sometimes nothing more than a hash blessed into a class. It's properties could be simply listed by iterating over the keys. However more complex data structures can be present, so the safest option is always to use <code>Data::Dumper</code> to examine an object.
<langsyntaxhighlight lang="perl">{
package Point;
use Class::Spiffy -base;
Line 714 ⟶ 733:
say Dumper $p1;
say Dumper $c1;
say Dumper $c2;</langsyntaxhighlight>
{{out}}
<pre>$VAR1 = bless( {
Line 739 ⟶ 758:
Technically the code below is re-fetching tid and flags before returning them in a textual format.
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">class</span> <span style="color: #000000;">c</span> <span style="color: #7060A8;">nullable</span>
<span style="color: #004080;">integer</span> <span style="color: #004080;">int</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
Line 766 ⟶ 785:
<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}}
Line 779 ⟶ 798:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?
class Foo {
}
Line 787 ⟶ 806:
 
var_dump(get_object_vars($obj));
?></langsyntaxhighlight>
{{out}}
<pre>
Line 799 ⟶ 818:
 
=={{header|PicoLisp}}==
The function <code>methodsshow</code> can be used to print all methodsproperties 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">
<lang PicoLisp>
# The Rectangle class
(class +Rectangle +Shape)
Line 821 ⟶ 840:
(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 methodsproperties using the <code>methodshow</code> function.
 
<syntaxhighlight lang="text">
: (setq R (new '(+Rectangle) 0 0 30 20))
-> $177356065126400
 
: (methodsshow R)
$177715702441044 (+Rectangle)
-> ((draw> . +Rectangle) (perimeter> . +Rectangle) (area> . +Rectangle) (T . +Rectangle) (move> . +Shape))
dy 20
</lang>
dx 30
y 0
x 0
-> $177715702441044
</syntaxhighlight>
 
 
Line 841 ⟶ 865:
 
Here we find the properties of a <code>[DateTime]</code> object:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-Date | Get-Member -MemberType Property
</syntaxhighlight>
</lang>
 
{{Out}}
Line 866 ⟶ 890:
</pre>
The "Add" methods of a <code>[DateTime]</code> object:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-Date | Get-Member -MemberType Method -Name Add*
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 889 ⟶ 913:
The <code>[https://docs.python.org/3.5/library/functions.html#dir dir()]</code> function and Python's <code>[https://docs.python.org/3.5/library/inspect.html#module-inspect inspect]</code> module both will list properties.
 
<langsyntaxhighlight lang="python">class Parent(object):
__priv = 'private'
Line 970 ⟶ 994:
inspect.getmembers(chld)
#[('__class__', <class '__main__.Child'>), ..., ('args', (0, 'I', 'two')), ('args_bleh', "(0, 'I', 'two') bleh"), ('doNothing', <bound method Child.doNothing of Child(chld, 0, 'I', 'two')>), ('doStuff', <bound method Child.doStuff of Child(chld, 0, 'I', 'two')>), ('name', 'chld'), ('name_bleh', 'chld bleh'), ('own', "chld's own"), ('own_bleh', "chld's own bleh"), ('reBleh', <_sre.SRE_Pattern object at 0x10067bd20>), ('reBleh_bleh', '<_sre.SRE_Pattern object at 0x10067bd20> bleh')]
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 978 ⟶ 1,002:
Each is represented as an <tt>Attribute</tt> object that contains a bunch of info:
 
<syntaxhighlight lang="raku" perl6line>class Foo {
has $!a = now;
has Str $.b;
Line 988 ⟶ 1,012:
for $object.^attributes {
say join ", ", .name, .readonly, .container.^name, .get_value($object);
}</langsyntaxhighlight>
 
{{out}}
Line 1,013 ⟶ 1,037:
 
A simplistic example:
<langsyntaxhighlight lang="rexx">j=2
abc.j= -4.12
 
 
say 'variable abc.2 (length' length(abc.2)')=' abc.2</langsyntaxhighlight>
<br><br>
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX shows the "equivalent" to PL/I's PUT DATA for a simple variable */
/* put_data2('a.') to show all a.tail values isn't that easy :-) */
j=2
Line 1,030 ⟶ 1,054:
put_data:
Parse Arg variable
return(variable'='''value(variable)'''')</langsyntaxhighlight>
{{out}}
<pre>abc.2='-4.12'
Line 1,036 ⟶ 1,060:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Foo
@@xyz = nil
def initialize(name, age)
Line 1,064 ⟶ 1,088:
p Foo.class_variable_get(:@@xyz) #=> :xyz
p Foo.class_variable_set(:@@abc, 123) #=> 123
p Foo.class_variables #=> [:@@xyz, :@@abc]</langsyntaxhighlight>
 
=={{header|Scala}}==
===Java Interoperability===
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/MdkPxH6yTlS4W8TaXYxSgA Scastie (remote JVM)].
<langsyntaxhighlight Scalalang="scala">object ListProperties extends App {
private val obj = new {
val examplePublicField: Int = 42
Line 1,081 ⟶ 1,105:
println("\nAll declared fields (excluding inherited):")
clazz.getDeclaredFields.foreach(f => println(s"${f}}"))
}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
for names of slots defined in the class (excludes inherited):
<syntaxhighlight lang="smalltalk">someObject class instVarNames</syntaxhighlight>
for all slot names (incl. inherited):
<syntaxhighlight lang="text">someObject class allInstVarNames</syntaxhighlight>
to get a Dictionary (aka. HashTable) mapping names to values:
<syntaxhighlight lang="text">someObject class allInstVarNames collect:[:nm | nm -> (someObject instVarNamed:nm)] as:Dictionary</syntaxhighlight>
 
A class can make this a secret by redefining #instVar access to eg. raise an exception.
Notice: this is not considered good Smalltalk style - it should be used by debuggers and object inspectors only, except for special frameworks (such as code generators etc.).
 
=={{header|Tcl}}==
Line 1,087 ⟶ 1,122:
 
For objects supporting this protocol, you can list all options by invoking the <tt>configure</tt> method without arguments (result split over multiple lines for readability):
<langsyntaxhighlight Tcllang="tcl">% package require Tk
8.6.5
% . configure
Line 1,097 ⟶ 1,132:
{-highlightcolor highlightColor HighlightColor #000000 #000000}
{-highlightthickness highlightThickness HighlightThickness 0 0} {-padx padX Pad 0 0} {-pady padY Pad 0 0}
{-takefocus takeFocus TakeFocus 0 0} {-visual visual Visual {} {}} {-width width Width 0 0}</langsyntaxhighlight>
 
Two-element sublists (eg <tt>-bd -borderwidth</tt>) represent aliases, and five-element sublists are of the form <tt>{optionName dbName dbClass defaultValue currentValue}</tt>. <tt>dbName</tt> and <tt>dbClass</tt> are related to how the option is specified in the <i>option database</i>.
Line 1,103 ⟶ 1,138:
Simply listing the option names is like this:
 
<langsyntaxhighlight Tcllang="tcl">% lmap o [. configure] {if {[llength $o] == 2} continue else {lindex $o 0}}
-borderwidth -class -menu -relief -screen -use -background -colormap -container -cursor -height
-highlightbackground -highlightcolor -highlightthickness -padx -pady -takefocus -visual -width</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Imports System.Reflection
 
Module Module1
Line 1,140 ⟶ 1,175:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>{ Name = PublicNumber, Value = 4 }
Line 1,152 ⟶ 1,187:
 
Note that, since attributes are stored internally as a map, the order in which the property names appear is undefined.
<langsyntaxhighlight ecmascriptlang="wren">#! instance_methods(m, n, o)
#! instance_properties(p, q, r)
class C {
Line 1,172 ⟶ 1,207:
var c = C.new() // create an object of type C
System.print("List of properties available for object 'c':")
for (property in c.type.attributes.self["instance_properties"]) System.print(property.key)</langsyntaxhighlight>
 
{{out}}
Line 1,186 ⟶ 1,221:
 
Every object has a "properties" method, which returns a list of property names [for that object].
<langsyntaxhighlight lang="zkl">properties:=List.properties;
properties.println();
List(1,2,3).property(properties[0]).println(); // get value
List(1,2,3).Property(properties[0])().println(); // method that gets value
List(1,2,3).BaseClass(properties[0]).println(); // another way to get value</langsyntaxhighlight>
{{out}}
<pre>
162

edits