Getting properties by using reflection
The type.TypeInfo object includes a property called
Properties, which contains a list of type properties. Each item in that
list includes metadata properties such as the name (Name) and a short
description (ShortDescription).
Because of performance implications and the inability to find errors at compile time, only use reflection if there is no other way to do what you need.
To examine how reflection provides information about class properties, paste the following code into the Gosu Scratchpad.
var object = "This is a string"
var propNames = ""
var props = (typeof object).TypeInfo.Properties
for (prop in props) {
propNames = propNames + prop.Name + " "
}
print(propNames)
This code prints lines similar to the following output.
Class Bytes Empty CASE_INSENSITIVE_ORDER Digits AsBigDecimal length size HasContent
NotBlank Alpha AlphaSpace Alphanumeric AlphanumericSpace Numeric NumericSpace Whitespace
Array syntax for getting a property by using reflection
Gosu also provides a concise associative array syntax to access properties by reflection. This syntax uses square brackets to access properties, similar to using arrays. The property name is case sensitive.
[] operator applies to all objects and has the typical meaning for
List, Array, and Map objects. For
other objects, the [] syntax performs a reflective look-up.For example, paste the following code into the Gosu Scratchpad.
var dateObject = new Date()
var propertyName = "Hour"
// Get a property name using reflection
print(dateObject[propertyName])
If the time is currently 5:00 a.m., this code prints the following output.
5
public class ObjClass {
property get MyProperty() : String {
return "Default value for MyProperty"
}
}ObjClass and uses array
syntax to access the MyProperty property by
reflection:var obj = new ObjClass()
var val = obj["MyProperty"]var obj = new ObjClass()
var val = (typeof obj).TypeInfo.getProperty("MyProperty").Accessor.getValue(obj)