Reflection/List properties

From Rosetta Code
Reflection/List properties
You are encouraged to solve this task according to the task description, using any language you may know.

The goal is to get the properties of an object, as names, values or both.

Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.


Fortran offers services somewhat as desired, at two levels. Suppose X is the name of some variable. Then, WRITE (6,*) X would send to file unit six (the modern default unit number for "standard output"), the value of X, whatever its type - be it an array, a complex number, an integer, a character variable, or, (with F90 and later) an aggregate or "structure", all with appropriate formats for each part, single or double precision, etc. This is the "free-format" or "list-directed" style, signified by the asterisk in place of a format code or the label of a FORMAT statement. With arrays, repeated values are shown with a repetition count, as in 66*303 meaning sixty-six values of 303. Alas, the @ symbol is not used. Thus, inspection of the style of such output will reveal whether X was an integer, etc.

The second level requires slightly more effort: a declaration such as NAMELIST /STUFF/ X enables the use of a statement such as WRITE (6,STUFF) whereupon each item's value will be prefixed with its name in the style of an assignment statement, as in X = 2.7182818 if X were to be the name of a simple floating-point variable.

There may be a list of items, not just the lone X and these proceedings apply to READ statements also.


import java.lang.reflect.Field;
public class ListFields {
public int examplePublicField = 42;
private boolean examplePrivateField = true;
public static void main(String[] args) throws IllegalAccessException {
ListFields obj = new ListFields();
Class clazz = obj.getClass();
System.out.println("All public fields (including inherited):");
for (Field f : clazz.getFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
System.out.println("All declared fields (excluding inherited):");
for (Field f : clazz.getDeclaredFields()) {
System.out.printf("%s\t%s\n", f, f.get(obj));
All public fields (including inherited):
public int ListFields.examplePublicField	42

All declared fields (excluding inherited):
public int ListFields.examplePublicField	42
private boolean ListFields.examplePrivateField	true


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 for. Object.getOwnPropertyNames().

var obj = Object.create({
name: 'proto',
proto: true,
doNothing: function() {}
}, {
name: {value: 'obj', writable: true, configurable: true, enumerable: true},
obj: {value: true, writable: true, configurable: true, enumerable: true},
'non-enum': {value: 'non-enumerable', writable: true, enumerable: false},
doStuff: {value: function() {}, enumerable: true}
// get enumerable properties on an object and its ancestors
function get_property_names(obj) {
var properties = [];
for (var p in obj) {
return properties;
//["name", "obj", "doStuff", "proto", "doNothing"]
//["name", "obj", "non-enum", "doStuff"]
//["name", "obj", "doStuff"]
//[["name", "obj"], ["obj", true], ["doStuff", function()]]


Works with: Julia version 0.6
for obj in (Int, 1, 1:10, collect(1:10), now())
println("\nObject: $obj\nDescription:")
Object: Int64
Int64 <: Signed

Object: 1
Int64 1

Object: 1:10
  start: Int64 1
  stop: Int64 10

Object: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array{Int64}((10,)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Object: 2017-10-04T18:03:33.691
  instant: Base.Dates.UTInstant{Base.Dates.Millisecond}
    periods: Base.Dates.Millisecond
      value: Int64 63642823413691


// version 1.1
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
open class BaseExample(val baseProp: String) {
protected val protectedProp: String = "inherited protected value"
class Example(val prop1: String, val prop2: Int, baseProp: String) : BaseExample(baseProp) {
private val privateProp: String = "private value"
val prop3: String
get() = "property without backing field"
val prop4 by lazy { "delegated value" }
fun main(args: Array<String>) {
val example = Example(prop1 = "abc", prop2 = 1, baseProp = "inherited public value")
val props = Example::class.memberProperties
for (prop in props) {
prop.isAccessible = true // makes non-public properties accessible
println("${} -> ${prop.get(example)}")
privateProp   -> private value
prop1         -> abc
prop2         -> 1
prop3         -> property without backing field
prop4         -> delegated value
baseProp      -> inherited public value
protectedProp -> inherited protected value


obj = script("MyClass").new() = 23 = 42
-- ...
-- show obj's property names and values
cnt = obj.count
repeat with i = 1 to cnt
put obj.getPropAt(i)&" = "&obj[i]
end repeat
-- "bar = 42"
-- "foo = 23"


#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo : NSObject {
int exampleIvar;
@property (nonatomic) double exampleProperty;
@implementation Foo
- (instancetype)init {
self = [super init];
if (self) {
exampleIvar = 42;
_exampleProperty = 3.14;
return self;
int main() {
id obj = [[Foo alloc] init];
Class clazz = [obj class];
NSLog(@"\Instance variables:");
unsigned int ivarCount;
Ivar *ivars = class_copyIvarList(clazz, &ivarCount);
for (unsigned int i = 0; i < ivarCount; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
const char *typeEncoding = ivar_getTypeEncoding(ivar);
// for simple types we can use Key-Value Coding to access it
// but in general we will have to use object_getIvar and cast it to the right type of function
// corresponding to the type of the instance variable
id value = [obj valueForKey:@(name)];
NSLog(@"%s\t%s\t%@", name, typeEncoding, value);
unsigned int propCount;
objc_property_t *properties = class_copyPropertyList([Foo class], &propCount);
for (unsigned int i = 0; i < propCount; i++) {
objc_property_t p = properties[i];
const char *name = property_getName(p);
const char *attributes = property_getAttributes(p);
// for simple types we can use Key-Value Coding to access it
// but in general we will have to use objc_msgSend to call the getter,
// casting objc_msgSend to the right type of function corresponding to the type of the getter
id value = [obj valueForKey:@(name)];
NSLog(@"%s\t%s\t%@", name, attributes, value);
return 0;
Instance variables:
exampleIvar	i	42
_exampleProperty	d	3.14

exampleProperty	Td,N,V_exampleProperty	3.14

Perl 6[edit]

You can get a list of an object's attributes (instance variables) using .^attributes, which is part of the Meta Object Protocol..
Each is represented as an Attribute object that contains a bunch of info:

class Foo {
has $!a = now;
has Str $.b;
has Int $.c is rw;
my $object = b => "Hello", c => 42;
for $object.^attributes {
say join ", ", .name, .readonly, .container.^name, .get_value($object);
$!a, True, Any, Instant:1470517602.295992
$!b, True, Str, Hello
$!c, False, Int, 42

Public attributes (in this case, $.b and $.c) are really just attributes for which the compiler also auto-generates a method of the same name. See Reflection/List_methods#Perl_6.


class Foo {
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
array(2) {


PUT DATA(X) will send to SYSOUT the value(s) of X prefixed by the name(s), formatted appropriately for single/double bit/integer/real/complex, character, etc. whether X is a single datum, an array, a data structure, etc. A list of items may be specified, not just the single X and for input, the word is GET. Similarly, PUT STRING(TEXT) DATA(X) will place such output in a character variable, which may have to be large...


In PowerShell everything is an object. To find any type of member of any object use the Get-Member Cmdlet.

Here we find the properties of a [DateTime] object:

Get-Date | Get-Member -MemberType Property
   TypeName: System.DateTime

Name        MemberType Definition                       
----        ---------- ----------                       
Date        Property   datetime Date {get;}             
Day         Property   int Day {get;}                   
DayOfWeek   Property   System.DayOfWeek DayOfWeek {get;}
DayOfYear   Property   int DayOfYear {get;}             
Hour        Property   int Hour {get;}                  
Kind        Property   System.DateTimeKind Kind {get;}  
Millisecond Property   int Millisecond {get;}           
Minute      Property   int Minute {get;}                
Month       Property   int Month {get;}                 
Second      Property   int Second {get;}                
Ticks       Property   long Ticks {get;}                
TimeOfDay   Property   timespan TimeOfDay {get;}        
Year        Property   int Year {get;}                  

The "Add" methods of a [DateTime] object:

Get-Date | Get-Member -MemberType Method -Name Add*
   TypeName: System.DateTime

Name            MemberType Definition                            
----            ---------- ----------                            
Add             Method     datetime Add(timespan value)          
AddDays         Method     datetime AddDays(double value)        
AddHours        Method     datetime AddHours(double value)       
AddMilliseconds Method     datetime AddMilliseconds(double value)
AddMinutes      Method     datetime AddMinutes(double value)     
AddMonths       Method     datetime AddMonths(int months)        
AddSeconds      Method     datetime AddSeconds(double value)     
AddTicks        Method     datetime AddTicks(long value)         
AddYears        Method     datetime AddYears(int value)          


The dir() function and Python's inspect module both will list properties.

class Parent(object):
__priv = 'private'
def __init__(self, name): = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
def doNothing(self):
import re
class Child(Parent):
# prefix for "private" fields
__rePrivate = re.compile('^_(Child|Parent)__')
# used when setting dynamic property values
__reBleh = re.compile('\Wbleh$')
def reBleh(self):
return self.__reBleh
def __init__(self, name, *args):
super(Child, self).__init__(name)
self.args = args
def __dir__(self):
myDir = filter(
# filter out private fields
lambda p: not self.__rePrivate.match(p),
list(set( \
sum([dir(base) for base in type(self).__bases__], []) \
+ type(self).__dict__.keys() \
+ self.__dict__.keys() \
return myDir + map(
# dynamic properties
lambda p: p + '_bleh',
# don't add dynamic properties for methods and other special properties
lambda p: (p[:2] != '__' or p[-2:] != '__') and not callable(getattr(self, p)),
def __getattr__(self, name):
if name[-5:] == '_bleh':
# dynamic '_bleh' properties
return str(getattr(self, name[:-5])) + ' bleh'
if hasattr(super(Child, chld), '__getattr__'):
return super(Child, self).__getattr__(name)
raise AttributeError("'%s' object has no attribute '%s'" % (type(self).__name__, name))
def __setattr__(self, name, value):
if name[-5:] == '_bleh':
# skip backing properties that are methods
if not (hasattr(self, name[:-5]) and callable(getattr(self, name[:-5]))):
setattr(self, name[:-5], self.reBleh.sub('', value))
elif hasattr(super(Child, self), '__setattr__'):
super(Child, self).__setattr__(name, value)
elif hasattr(self, '__dict__'):
self.__dict__[name] = value
def __repr__(self):
return '%s(%s, %s)' % (type(self).__name__,, str(self.args).strip('[]()'))
def doStuff(self):
return (1+1.0/1e6) ** 1e6
par = Parent('par')
par.parent = True
#['_Parent__priv', '__class__', ..., 'doNothing', 'name', 'parent']
#[('_Parent__priv', 'private'), ('__class__', <class '__main__.Parent'>), ..., ('doNothing', <bound method Parent.doNothing of <__main__.Parent object at 0x100777650>>), ('name', 'par'), ('parent', True)]
chld = Child('chld', 0, 'I', 'two')
chld.own = "chld's own"
#['__class__', ..., 'args', 'args_bleh', 'doNothing', 'doStuff', 'name', 'name_bleh', 'own', 'own_bleh', 'reBleh', 'reBleh_bleh']
#[('__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')]


(This REXX version is modeled after the   PL/I   entry.)

The   say   instruction can display a value (it's contents) to the console (terminal) as well as it's length   (the number of characters in its value).

Since   everything   in REXX is a character string, the   type   of the variable (character) need not be explicitly expressed.

A simplistic example:

abc.j= -4.12
say 'variable abc.2 (length' length(abc.2)')=' abc.2


class Foo
@@xyz = nil
def initialize(name, age)
@name, @age = name, age
def add_sex(sex)
@sex = sex
p foo ="Angel", 18) #=> #<Foo:0x0000000305a688 @name="Angel", @age=18>
p foo.instance_variables #=> [:@name, :@age]
p foo.instance_variable_defined?(:@age) #=> true
p foo.instance_variable_get(:@age) #=> 18
p foo.instance_variable_set(:@age, 19) #=> 19
p foo #=> #<Foo:0x0000000305a688 @name="Angel", @age=19>
p foo.instance_variables #=> [:@name, :@age, :@sex]
p foo #=> #<Foo:0x0000000305a688 @name="Angel", @age=19, @sex=:woman>
foo.instance_variable_set(:@bar, nil)
p foo.instance_variables #=> [:@name, :@age, :@sex, :@bar]
p Foo.class_variables #=> [:@@xyz]
p Foo.class_variable_defined?(:@@xyz) #=> true
p Foo.class_variable_get(:@@xyz) #=> nil
p Foo.class_variable_set(:@@xyz, :xyz) #=> :xyz
p Foo.class_variable_get(:@@xyz) #=> :xyz
p Foo.class_variable_set(:@@abc, 123) #=> 123
p Foo.class_variables #=> [:@@xyz, :@@abc]


Tcl objects do not have properties exactly (externally visible variables), though a common idiom pioneered by Tk is options exposed by the configure and cget commands.

For objects supporting this protocol, you can list all options by invoking the configure method without arguments (result split over multiple lines for readability):

% package require Tk
% . configure
{-bd -borderwidth} {-borderwidth borderWidth BorderWidth 0 0} {-class class Class Toplevel Tclsh}
{-menu menu Menu {} {}} {-relief relief Relief flat flat} {-screen screen Screen {} {}} {-use use Use {} {}}
{-background background Background #d9d9d9 #d9d9d9} {-bg -background} {-colormap colormap Colormap {} {}}
{-container container Container 0 0} {-cursor cursor Cursor {} {}} {-height height Height 0 0}
{-highlightbackground highlightBackground HighlightBackground #d9d9d9 #d9d9d9}
{-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 -bd -borderwidth) represent aliases, and five-element sublists are of the form {optionName dbName dbClass defaultValue currentValue}. dbName and dbClass are related to how the option is specified in the option database.

Simply listing the option names is like this:

% 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


In zkl, properties are static read only informational data.

Every object has a "properties" method, which returns a list of property names [for that object].;
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