Reflection/List properties: Difference between revisions
Content deleted Content added
PascalABC.NET |
|||
(13 intermediate revisions by 9 users not shown) | |||
Line 12:
=={{header|C sharp}}==
{{works with|C sharp|7}}
<
using System.Collections.Generic;
using System.Linq;
Line 45:
}
}</
{{out}}
<pre>
Line 56:
=={{header|D}}==
<
struct S {
Line 90:
printProperties!S;
printProperties!C;
}</
{{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]
</pre>
=={{header|Elena}}==
ELENA
<
import system'dynamic;
import extensions;
Line 105 ⟶ 124:
class MyClass
{
}
public program()
{
Line 117 ⟶ 136:
this Y := "String";
};
MyClass.__getProperties().forEach::(p)
{
console.printLine("o.",p,"=",
}
}</
{{out}}
<pre>
Line 131 ⟶ 150:
=={{header|Factor}}==
Mirrors present an object's slots and slot values as an associative structure.
<
TUPLE: foo
Line 140 ⟶ 159:
"apple" "banana" 200 <foo> <mirror>
[ >alist ] [ object-slots ] bi [ . ] bi@</
{{out}}
<pre>
Line 175 ⟶ 194:
=={{header|Go}}==
<
import (
Line 208 ⟶ 227:
}
fmt.Println()
}</
{{out}}
<pre>
Line 224 ⟶ 243:
=={{header|Groovy}}==
{{trans|Java}}
<
@SuppressWarnings("unused")
Line 247 ⟶ 266:
}
}
}</
{{out}}
<pre>All public fields (including inherited):
Line 267 ⟶ 286:
=={{header|Java}}==
<
public class ListFields {
Line 287 ⟶ 306:
}
}
}</
{{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>.
<
name: 'proto',
proto: true,
Line 332 ⟶ 351:
Object.entries(obj);
//[["name", "obj"], ["obj", true], ["doStuff", function()]]
</syntaxhighlight>
=={{header|jq}}==
{{works with|jq}}
Various properties of JSON values are directly accessible via the
built-in functions `type`, `length` (except for booleans), and, for
JSON objects, `keys` and `keys_unsorted`:
* `type` returns the JSON type;
* `length` returns an array's length, the number of (distinct) keys of an object, the absolute value of a number, and 0 for `null`;
Note that gojq (the Go implementation of jq) does not support `keys_unsorted`.
Other properties can be ascertained programmatically.
See e.g. '''schema.jq''' (https://gist.github.com/pkoppstein/a5abb4ebef3b0f72a6ed) for a schema-inference engine for JSON written in jq; the inferred schemas are themselves JSON documents.
'''Example'''
<syntaxhighlight lang="jq">
# Use jq's built-ins to generate a (recursive) synopsis of .
def synopsis:
if type == "boolean" then "Type: \(type)"
elif type == "object"
then "Type: \(type) length:\(length)",
(keys_unsorted[] as $k
| "\($k): \(.[$k] | synopsis )")
else "Type: \(type) length: \(length)"
end;
true, null, [1,2], {"a": {"b": 3, "c": 4}, "x": "Rosetta Code"}, now
| ("\n\(.) ::", synopsis)
</syntaxhighlight>
{{out}}
<pre>
true ::
Type: boolean
null ::
Type: null length: 0
[1,2] ::
Type: array length: 2
{"a":{"b":3,"c":4},"x":[0,1]} ::
Type: object length:2
a: Type: object length:2
a: b: Type: number length: 3
a: c: Type: number length: 4
x: Type: string length: 12
1629526284.540229 ::
Type: number length: 1629526284.540229
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
println("\nObject: $obj\nDescription:")
dump(obj)
end</
{{out}}
Line 370 ⟶ 442:
=={{header|Kotlin}}==
<
import kotlin.reflect.full.memberProperties
Line 395 ⟶ 467:
println("${prop.name.padEnd(13)} -> ${prop.get(example)}")
}
}</
{{out}}
Line 409 ⟶ 481:
=={{header|Lingo}}==
<
obj.foo = 23
obj.bar = 42
Line 419 ⟶ 491:
repeat with i = 1 to cnt
put obj.getPropAt(i)&" = "&obj[i]
end repeat</
{{Out}}
Line 428 ⟶ 500:
=={{header|Lua}}==
<
b = 2.0
c = "hello world"
Line 445 ⟶ 517:
listProperties(_G)
print("Package properties")
listProperties(package)</
{{out}}
<pre>Global properties
Line 471 ⟶ 543:
=={{header|Nanoquery}}==
<
class Fields
declare static field1 = "this is a static field. it will not be listed"
Line 482 ⟶ 554:
for fieldname in Fields.getFieldNames()
println fieldname
end</
{{out}}
Line 489 ⟶ 561:
field4</pre>
=={{header|Nim}}==
<
Foo = object
a: float
b: string
c: seq[int]
let f = Foo(a: 0.9, b: "hi", c: @[1,2,3])
for n, v in f.fieldPairs:
echo n, ": ", v</
{{out}}
<pre>a: 0.9
Line 503 ⟶ 575:
=={{header|Objective-C}}==
<
#import <objc/runtime.h>
Line 558 ⟶ 630:
return 0;
}</
{{out}}
<pre>
Line 576 ⟶ 648:
Many of these options are also supported by other REXX implementations.
<
/* test values */
d.1=''
Line 620 ⟶ 692:
Say ol
End
Say hdr</
{{out}}
<pre> A B I L M N O S U V W X 9 datatype(v)
Line 637 ⟶ 709:
123 1 0 1 0 0 1 0 1 0 0 1 1 1 NUM
A B I L M N O S U V W X 9 datatype(v)</pre>
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
uses System, System.Reflection;
type
MyClass = class
private
auto property NumberPrivate: integer := 666;
public
auto property Number: integer := 3;
end;
begin
var flags := BindingFlags.Instance or BindingFlags.Static
or BindingFlags.Public or BindingFlags.NonPublic
or BindingFlags.DeclaredOnly;
var obj := new MyClass;
typeof(MyClass).GetProperties(flags).Select(p -> (p.Name,p.GetValue(obj))).PrintLines;
end.
</syntaxhighlight>
{{out}}
<pre>
(NumberPrivate,666)
(Number,3)
</pre>
=={{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.
<
package Point;
use Class::Spiffy -base;
Line 661 ⟶ 761:
say Dumper $p1;
say Dumper $c1;
say Dumper $c2;</
{{out}}
<pre>$VAR1 = bless( {
Line 685 ⟶ 785:
You should certainly be prepared for them to return NULL for unrecognised field names and types.<br>
Technically the code below is re-fetching tid and flags before returning them in a textual format.
<!--<syntaxhighlight lang="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>
<span style="color: #008080;">public</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">atm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2.3</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">str</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"4point5"</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">seq</span>
<span style="color: #008080;">public</span><span style="color: #0000FF;">:</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">obj</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"an object"</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">c</span> <span style="color: #000000;">child</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: #000000;">c</span> <span style="color: #000000;">c_instance</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new</span><span style="color: #0000FF;">()</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: #008080;">function</span> <span style="color: #000000;">nulls</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"NULL"</span><span style="color: #0000FF;">:</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">fields</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;">fields</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;">fields</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: #008080;">not</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: #000080;font-style:italic;">-- (exclude foo/bar)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nulls</span><span style="color: #0000FF;">(</span><span style="color: #000000;">structs</span><span style="color: #0000FF;">:</span><span style="color: #000000;">get_field_type</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: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nulls</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: #004080;">object</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nulls</span><span style="color: #0000FF;">(</span><span style="color: #000000;">structs</span><span style="color: #0000FF;">:</span><span style="color: #000000;">fetch_field</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c_instance</span><span style="color: #0000FF;">,</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</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;">"type:%-11s, name:%-5s, flags:%s, value:%v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">name</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 722 ⟶ 826:
=={{header|PHP}}==
<
class Foo {
}
Line 730 ⟶ 834:
var_dump(get_object_vars($obj));
?></
{{out}}
<pre>
Line 740 ⟶ 844:
}
</pre>
=={{header|PicoLisp}}==
The function <code>show</code> can be used to print all properties of an object.
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 properties using the <code>show</code> function.
<syntaxhighlight lang="text">
: (setq R (new '(+Rectangle) 0 0 30 20))
-> $177356065126400
: (show R)
$177715702441044 (+Rectangle)
dy 20
dx 30
y 0
x 0
-> $177715702441044
</syntaxhighlight>
=={{header|PL/I}}==
Line 748 ⟶ 893:
Here we find the properties of a <code>[DateTime]</code> object:
<syntaxhighlight lang="powershell">
Get-Date | Get-Member -MemberType Property
</syntaxhighlight>
{{Out}}
Line 773 ⟶ 918:
</pre>
The "Add" methods of a <code>[DateTime]</code> object:
<syntaxhighlight lang="powershell">
Get-Date | Get-Member -MemberType Method -Name Add*
</syntaxhighlight>
{{Out}}
<pre>
Line 796 ⟶ 941:
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.
<
__priv = 'private'
Line 877 ⟶ 1,022:
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>
=={{header|Raku}}==
Line 885 ⟶ 1,030:
Each is represented as an <tt>Attribute</tt> object that contains a bunch of info:
<syntaxhighlight lang="raku"
has $!a = now;
has Str $.b;
Line 895 ⟶ 1,040:
for $object.^attributes {
say join ", ", .name, .readonly, .container.^name, .get_value($object);
}</
{{out}}
Line 920 ⟶ 1,065:
A simplistic example:
<
abc.j= -4.12
say 'variable abc.2 (length' length(abc.2)')=' abc.2</
<br><br>
===version 2===
<
/* put_data2('a.') to show all a.tail values isn't that easy :-) */
j=2
Line 937 ⟶ 1,082:
put_data:
Parse Arg variable
return(variable'='''value(variable)'''')</
{{out}}
<pre>abc.2='-4.12'
Line 943 ⟶ 1,088:
=={{header|Ruby}}==
<
@@xyz = nil
def initialize(name, age)
Line 971 ⟶ 1,116:
p Foo.class_variable_get(:@@xyz) #=> :xyz
p Foo.class_variable_set(:@@abc, 123) #=> 123
p Foo.class_variables #=> [:@@xyz, :@@abc]</
=={{header|Scala}}==
===Java Interoperability===
{{Out}}Best seen running in your browser [https://scastie.scala-lang.org/MdkPxH6yTlS4W8TaXYxSgA Scastie (remote JVM)].
<
private val obj = new {
val examplePublicField: Int = 42
Line 988 ⟶ 1,133:
println("\nAll declared fields (excluding inherited):")
clazz.getDeclaredFields.foreach(f => println(s"${f}}"))
}</
=={{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 994 ⟶ 1,150:
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):
<
8.6.5
% . configure
Line 1,004 ⟶ 1,160:
{-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}</
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,010 ⟶ 1,166:
Simply listing the option names is like this:
<
-borderwidth -class -menu -relief -screen -use -background -colormap -container -cursor -height
-highlightbackground -highlightcolor -highlightthickness -padx -pady -takefocus -visual -width</
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 1,047 ⟶ 1,203:
End Sub
End Module</
{{out}}
<pre>{ Name = PublicNumber, Value = 4 }
Line 1,054 ⟶ 1,210:
{ Name = _PublicNumber, Value = 4 }
{ Name = _PrivateNumber, Value = 2 }</pre>
=={{header|Wren}}==
Wren doesn't currently have reflection as such but it's possible to identify a class's properties 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 property 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 properties available for object 'c':")
for (property in c.type.attributes.self["instance_properties"]) System.print(property.key)</syntaxhighlight>
{{out}}
<pre>
List of properties available for object 'c':
r
q
p
</pre>
=={{header|zkl}}==
Line 1,059 ⟶ 1,249:
Every object has a "properties" method, which returns a list of property names [for that object].
<
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</
{{out}}
<pre>
|