Skip to main content

Reflection

lib/reflect/ provides first-class reflection over classes, methods, fields, constructors, and annotations.

Types

TypeFileRole
Classlib/reflect/Class.mtA reflected class declaration.
Methodlib/reflect/Method.mtA reflected method on a class.
Fieldlib/reflect/Field.mtA reflected field.
Constructorlib/reflect/Constructor.mtA reflected constructor.
Annotationlib/reflect/Annotation.mtA reflected annotation instance.
Librarylib/reflect/Library.mtLoaded .mtcLib introspection.
Modifierlib/reflect/Modifier.mtAccess modifier flags.

Looking up a Class

import * from "lib/reflect/Class.mt";

Class c = Class::forName("Service");
print(c.getName());

Listing Methods

import * from "lib/reflect/Class.mt";
import * from "lib/reflect/Method.mt";

Class c = Class::forName("Service");
ArrayList<Method> methods = c.getDeclaredMethods();
for (Method m : methods) {
print(m.getName() + " : " + m.getReturnType().getName());
}

Reading Annotations

Only @Retention(RUNTIME) annotations survive into runtime metadata.

import * from "lib/reflect/Class.mt";
import * from "lib/reflect/Method.mt";
import * from "lib/reflect/Annotation.mt";

Class c = Class::forName("Service");
Method m = c.getDeclaredMethod("ping", 0);
Annotation? t = m.getAnnotation("Timeout");
if (t != null) {
print(t.getInt("ms"));
}

Invocation

Constructor ctor = c.getConstructor(0);
Object[] args = new Object[0];
Object instance = ctor.newInstance(args);

Method m = c.getDeclaredMethod("greet", 0);
m.invoke(instance, args);

newInstance and invoke are instance methods — call them with . on a Constructor or Method value returned from reflection. Both take a Object[] of arguments.

See Also