Reflection
import "std/core" (included in import "std") · namespace std.core
Reflection lets code work with classes it does not know in advance: an ORM that maps rows to models, a serializer, a validator, a dependency injector. reflect(User) (or ClassInfo.of(anObject)) gives a ClassInfo that lists a class's fields, reads and writes them through any, creates objects, calls methods by name, and returns the decorators written on the class and its members, with their arguments.
import "std"
@Table("users")
class User {
@Column("user_id") @PrimaryKey
public id: int
@Column("email_address") @MaxLength(255)
public email: string
public age: int?
constructor() { self.id = 0; self.email = ""; self.age = null }
}
fn main() {
let info = reflect(User)
print(info.name + " -> table " + info.decorator("Table").text(0))
for (f in info.fields()) {
let col = f.decorator("Column")
print(" " + f.toString() + (col == null ? "" : " as " + col.text(0)))
}
// A row from a database, into a new User.
let row = new HashMap<string, any>()
row["user_id"] = 7
row["email_address"] = "ada@example.com"
let u = new User()
for (f in info.fields()) {
let c = f.decorator("Column")
let key = c == null ? f.name : c.text(0)
if (row.containsKey(key)) { f.set(u, row[key]) }
}
print("${u.id} ${u.email} ${u.age}")
print(info.field("email").decorator("MaxLength").number(0, 0))
print(ClassInfo.of(u) == info)
}User -> table users
id: int as user_id
email: string as email_address
age: int?
7 ada@example.com null
255
true- Decorators go on classes, fields, methods and constructors:
@Nameor@Name(args). Arguments are literals (strings, numbers,true/false) or names (@HasMany(Post)gives the text"Post"). The names are yours: the compiler only records them.text(i),number(i, fallback)andarg(i)read the arguments. Arguments can be named, after the positional ones:@Column("email", length: 255, unique: true);get("length"),text("length"),number("length", 0),flag("unique", false)andhasArg("length")read those, andkeyslists each argument's name (""for a positional one). Fields come base class first, with private and readonly fields included (reflection is for library code).
get(obj)boxes the value;set(obj, v)takes ananythat fits the field, converting it when it can (what a database row holds rarely matches a model's types exactly):- an integer field (
int,long,byte, ...) takes a whole number in its range: an integer, a bool, a float without a fraction (12.0), or a string holding one ("42", as databases give DECIMAL and BIGINT); - a float field takes any number or a numeric string (
"19.99"); - a bool field takes a bool,
0or1, or"true"/"false","t"/"f","yes"/"no","1"/"0"; - a string field takes a string; a class field an object of the class (or
null); aT?fieldnullor what aTfield takes; an enum field the enum or its number.
Anything else is a
ValueErrornaming the field, its type and the value (field 'age' of User (int) cannot hold "4x"). Interface and function fields can be read but not written, and value structs and fixed arrays neither (canGet(),canSet()).- an integer field (
- Nullability as written:
isNullable()is true for a field written with?(age: int?,joined: DateTime?), andtypeNamekeeps the?. A class-typed field written without one (created: DateTime) reports false, though it can hold null: what an ORM needs to makeNOT NULLcolumns. - Creating objects.
info.create()isnew User(), andinfo.create(["Ada", 36])calls the constructor taking two arguments that they fit (converted assetconverts).constructors()lists them andcanCreate()says whether one takes no arguments. An abstract class has none. This is what a generic repository needs: insideclass Repository<T>,reflect(T)is the classTstands for in each use (Repository<User>reflectsUser), so it can make aTwithout being handed a factory. - Calling methods.
info.invoke(obj, "greet", ["Bob"])isobj.greet("Bob"): of the methods calledgreet(the class's own, then its base classes'), the one taking that many arguments that they fit. An overridden method runs the object's own version, as a normal call does. A static method takesnullforobj.method(name)gives theMethodInfo, whoseinvoke(obj, args)calls that one method;paramCount()andparams("string, int") describe it. Its result comes back as anany(nullfor none), and what it throws goes on. A method can be called this way when its parameters and result can go through anany(numbers, bools, strings, enums, objects,T?,any); one taking a function, say, cannot (canInvoke()). - Properties.
info.properties()lists the class's properties (get name()/set name(v), its base classes' first), andproperty(name)finds one:p.get(obj)reads it through its getter,p.set(obj, value)assigns it through its setter (converted asFieldInfo.setconverts),typeNameis its type,isReadonly()says it has no setter, and its decorators are those on either accessor. The accessors are not inmethods(). An override of only the getter keeps its base class's setter. - In a static method,
reflect(Self)is the class the call names (see Self), so a base class can hydrate any model:User.hydrate(row)makes aUser. - What it costs. The compiler records a class only when its hierarchy (its root class and everything under it) has a decorator somewhere, or
reflect(...)names one of its classes; other classes have no tables, so programs that do not use reflection are unchanged. A recorded class costs about 250 bytes of code and 90 bytes of static tables per field, and nothing at run time until it is first reflected. There is oneClassInfoper class, made once, shared by every thread and never changed. A reflective read or write takes about 40 ns (a plain field access is under 1 ns), and finding aClassInfoagain is one atomic load. ClassInfo.of(x)isnullwhenxholds no object; for a class without recorded metadata it still knows the name and base, with no fields or methods (isReflected()is false), and it cannot be created or its methods called.ClassInfo.forName("app.SendInvoice")finds a class with reflection by its name (or by its bare name,"SendInvoice", when only one has it), andClassInfo.all(reflect(Job))lists every one that is or extendsJob. Since a decorator anywhere in a hierarchy gives the whole hierarchy reflection, one decorator on a base class makes all its subclasses findable: how a framework discovers its commands, jobs and listeners, or rebuilds a queued job from the class name it was stored under.
API
class Decorator
A decorator as written: @Column("email", 255) has the name "Column" and the arguments "email" and 255 (a name argument, @HasMany(Post), is text). Arguments may be named, after the positional ones: @Column("email", length: 255, unique: true); get("length") reads one by its name.
Constructors
new Decorator(name: string)
Fields
name: stringargs: Array<any>keys: Array<string>— Each argument's name, "" for a positional one (parallel to args).
Methods
fn get(key: string) -> any— The argument namedkey, or null when there is none.fn hasArg(key: string) -> bool— Whether an argument is namedkey.fn text(key: string) -> string— The argument namedkeyas text ("" when missing).fn number(key: string, fallback: long) -> long— The argument namedkeyas a number (fallbackwhen missing or not a whole number).fn flag(key: string, fallback: bool) -> bool— The argument namedkeyas a bool (fallbackwhen missing or not a bool).fn arg(i: int) -> any— Argument i, or null when there is no such argument.fn text(i: int) -> string— Argument i as text ("" when missing).fn number(i: int, fallback: long) -> long— Argument i as a number (fallbackwhen missing or not a whole number).fn toString() -> string
class FieldInfo
One field of a class: its name, type and decorators, and a way to read and write it on any object of that class.
Constructors
new FieldInfo(meta: byte*, owner: byte*)
Fields
name: string— The field's name.typeName: string— Its type as written in Grav ("int", "string", "User", ...).declaringClass: string— The class that declares it ("app.User").decorators: Array<Decorator>— Its decorators, in source order.
Methods
fn isReadonly() -> boolfn isPrivate() -> boolfn isProtected() -> boolfn isWeak() -> boolfn isNullable() -> bool— Whether its type was written to allow null:int?,DateTime?(a class-typed field written without?is not, though it can hold null).fn isEnum() -> bool— Whether its type (or the T of itsT?) is an enum.fn isObject() -> bool— Whether it holds an object: its type is a class or an interface (Array<int>,User,DateTime).fn canGet() -> bool— Whether get() works for its type (numbers, bools, strings, enums, objects, any, functions, T?).fn canSet() -> bool— Whether set() works for its type (as canGet, but not interfaces or functions).fn has(name: string) -> bool— Whether it has a decorator calledname.fn decorator(name: string) -> Decorator— Its first decorator calledname, or null.fn get(obj: any) -> any— The field's value inobj, an object of the declaring class or a subclass (ValueError otherwise).fn set(obj: any, value: any)— Storesvaluein the field ofobj. ValueError when the value does not fit its type, converted as the top of this file says (an int field takes 42, 42.0, true or "42" when in range; a float field any number or numeric string; a bool field true, 1 or "t"), a class field an object of that class or null, a T? field a T or null. Readonly and private fields are written too.fn toString() -> string
class MethodInfo
One method of a class as written: its name, whether it is static, and its decorators.
Constructors
new MethodInfo(meta: byte*, owner: string, kind: int)
Fields
name: stringdecorators: Array<Decorator>declaringClass: string— Its class ("app.User").params: string— Its parameter types as written ("string, int").result: string— Its result type ("string"; "" when it returns nothing).
Methods
fn paramCount() -> int— How many arguments it takes.fn canInvoke() -> bool— Whether invoke can call it: every parameter and its result can go through anany(numbers, bools, strings, enums, objects,T?, any).fn invoke(obj: any, args: Array<any> = new Array<any>()) -> any— Calls it onobj(ignored for a static method) withargs, each converted to its parameter's type; its result, or null when it returns nothing. What the method throws goes on.fn isStatic() -> boolfn isPrivate() -> boolfn isProtected() -> boolfn has(name: string) -> boolfn decorator(name: string) -> Decoratorfn toString() -> string
class PropertyInfo
A property (get name() -> T and/or set name(v: T)): read and written through its accessors. Its decorators are those on either accessor.
Constructors
new PropertyInfo(name: string, getter: MethodInfo, setter: MethodInfo)
Fields
name: stringtypeName: string— Its type as written ("string").declaringClass: string— The class that declares it (its getter's, else its setter's).decorators: Array<Decorator>
Methods
fn canGet() -> bool— Whether it has a getter / a setter that reflection can call.fn canSet() -> boolfn isReadonly() -> bool— Whether it has no setter at all.fn isStatic() -> boolfn isPrivate() -> boolfn isProtected() -> boolfn has(name: string) -> boolfn decorator(name: string) -> Decoratorfn get(obj: any) -> any— Its value inobj(ignored for a static property), from its getter.fn set(obj: any, value: any)— Sets it through its setter, convertingvalueas FieldInfo.set does.fn toString() -> string
class ClassInfo
What a class is at run time: reflect(User), or ClassInfo.of(anObject).
Constructors
new ClassInfo(t: byte*)
Static members
static fn forName(name: string) -> ClassInfo— The class calledname("app.SendInvoice", or "SendInvoice" when only one reflected class has that bare name); null when none does. Only classes with reflection are known: a class named by reflect(...), or any class in a hierarchy with a decorator (so one decorator on a framework base class makes every subclass findable by name).static fn all() -> Array<ClassInfo>— Every class with reflection (see forName), in declaration order; with a base, only the ones that are it or extend it (concrete or not).static fn all(base: ClassInfo) -> Array<ClassInfo>static fn of(value: any) -> ClassInfostatic fn listItems(value: any) -> Array<any>— The items ofvaluewhen it is a list of any element type (an Array<User> or Array<int>) asanys, for code that does not know the type: a serializer walking an object's fields. Null when it is not a list. (Going the other way, FieldInfo.set and invoke take an Array<any> for an Array<User> and convert each item.)static fn mapEntries(value: any) -> HashMap<string, any>— The entries ofvaluewhen it is a map with string keys (a HashMap<string, User>), asanys; null when it is not one.
Fields
name: string— The fully qualified name ("app.User").
Methods
fn simpleName() -> string— The name without its namespace ("User").fn base() -> ClassInfo— The base class, or null.fn isReflected() -> bool— Whether the compiler recorded fields, methods and decorators for it.fn decorators() -> Array<Decorator>— Its own decorators (not its base classes').fn has(name: string) -> boolfn decorator(name: string) -> Decoratorfn fields() -> Array<FieldInfo>— Every field, the base classes' first.fn ownFields() -> Array<FieldInfo>— The fields this class declares itself.fn field(name: string) -> FieldInfo— The field calledname(its own or a base class's), or null.fn properties() -> Array<PropertyInfo>— Every property, the base classes' first.fn ownProperties() -> Array<PropertyInfo>— The properties this class declares itself.fn property(name: string) -> PropertyInfo— The property calledname(its own or a base class's), or null.fn methods() -> Array<MethodInfo>— The methods this class declares itself (property accessors are its properties).fn method(name: string) -> MethodInfo— The method calledname: its own, else its base class's (the first overload; invoke picks among them). Null when there is none.fn invoke(obj: any, name: string, args: Array<any> = new Array<any>()) -> any— Calls methodnameonobjwithargs: the overload (its own, else a base class's) taking that many arguments that they fit.fn constructors() -> Array<MethodInfo>— Its constructors (none for an abstract class, or one without reflection).fn canCreate() -> bool— Whether create can make one with no arguments (a constructor taking none, or one whose parameters all have literal defaults).fn create(args: Array<any> = new Array<any>()) -> any— A new object of the class (new C(args...)): the constructor taking that many arguments that they fit.fn isSubclassOf(other: ClassInfo) -> bool— Whether this class isotheror extends it.fn isInstance(value: any) -> bool— Whethervalueholds an object of this class (or a subclass).fn toString() -> string