Reflective programming: Difference between revisions

Content deleted Content added
Techi2ee (talk | contribs)
Further reading: interwiki ca
 
(584 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Ability of a process to examine and modify itself}}
In [[computer science]], '''reflection''' is the process by which a [[computer program]] of the appropriate type can be modified in the process of being executed, in a manner that depends on abstract features of its code and its [[runtime]] behavior. Figuratively speaking, it is then said that the program has the ability to "observe" and possibly to modify its own structure and behavior. The programming paradigm driven by reflection is called ''reflective programming''.
{{distinguish|Reflection (computer graphics)}}
 
In [[computer science]], '''reflective programming''' or '''reflection''' is the ability of a [[Process (computing)|process]] to examine, [[Introspection (computer science)|introspect]], and modify its own structure and behavior.<ref>{{Citation | title = A Tutorial on Behavioral Reflection and its Implementation by Jacques Malenfant et al. | publisher = unknown | url = http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/malenfant.pdf | access-date = 23 June 2019 | archive-url = https://web.archive.org/web/20170821214626/http://www2.parc.com/csl/groups/sda/projects/reflection96/docs/malenfant/malenfant.pdf | archive-date = 21 August 2017 }}</ref>
Typically, reflection refers to runtime or dynamic reflection, though some programming languages support [[compile time]] or [[static]] reflection. It is most common in high-level virtual machine programming languages like [[Smalltalk]], and less common in lower-level programming languages like [[C (programming language)|C]].
 
==Historical background==
At the lowest level, machine code can be treated reflectively because the distinction between instruction and data becomes just a matter of how the information is treated by the computer. Normally, 'instructions' are 'executed' and 'data' are 'processed', however, the program can also treat instructions as data and therefore make reflective modifications.
The earliest computers were programmed in their native [[assembly language]]s, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using [[self-modifying code]]. As the bulk of programming moved to higher-level [[compiled languages]] such as [[ALGOL]], [[COBOL]], [[Fortran]], [[Pascal (programming language)|Pascal]], and [[C (programming language)|C]], this reflective ability largely disappeared until new programming languages with reflection built into their type systems appeared.{{Citation needed|date=July 2015}}
 
[[Brian Cantwell Smith]]'s 1982 doctoral dissertation introduced the notion of computational reflection in procedural [[programming languages]] and the notion of the [[meta-circular interpreter]] as a component of 3-Lisp.<ref>Brian Cantwell Smith, [http://hdl.handle.net/1721.1/15961 Procedural Reflection in Programming Languages], Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD dissertation, 1982.</ref><ref>Brian C. Smith. [http://publications.csail.mit.edu/lcs/specpub.php?id=840 Reflection and semantics in a procedural language] {{Webarchive|url=https://web.archive.org/web/20151213034343/http://publications.csail.mit.edu/lcs/specpub.php?id=840 |date=2015-12-13 }}. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Massachusetts, January 1982.</ref>
With higher level languages, when program [[source code]] is [[compiler|compiled]], information about the structure of the program is normally lost as [[Low-level programming language|lower level]] code (typically [[machine language]] code) is produced. If a system supports reflection, the structure is preserved as [[Metadata (computing)|metadata]] with the emitted code.
 
==Uses==
In languages that do not make a distinction between [[runtime]] and [[compile-time]] ([[Lisp programming language|Lisp]], [[Forth (programming language)|Forth]] and [[MUMPS (programming language)|MUMPS]], for example), there is no difference between compilation or [[Interpreted language|interpretation]] of code and reflection.
Reflection helps programmers make generic software libraries to display data, process different formats of data, perform [[serialization]] and deserialization of data for communication, or do bundling and unbundling of data for containers or bursts of communication.
 
Effective use of reflection almost always requires a plan: A design framework, encoding description, object library, a map of a database or entity relations.
==Reflective paradigm==
Reflective programming is a programming paradigm, used as an extension to the object-oriented programming paradigm, to add self-optimization to application programs, and to improve their flexibility. In this paradigm, computation is equated not with a program but with execution of a program. Other [[Imperative programming|imperative]] approaches, such as procedural or object-oriented paradigm, specify that there is a pre-determined sequence of operations (function or method calls), that modify any data or object they are given. In contrast, the reflective paradigm states that the sequence of operations won't be decided at compile time, rather the flow of sequence will be decided dynamically, based on the data that need to be operated upon, and what operation needs to be performed. The program will only code the sequence of how to identify the data and how to decide which operation to perform.
 
Reflection makes a language more suited to network-oriented code. For example, it assists languages such as [[Java (programming language)|Java]] to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection such as [[C (programming language)|C]] are required to use auxiliary compilers for tasks like [[Abstract Syntax Notation]] to produce code for serialization and bundling.
Any computation can be classified as either of two:
*Atomic - The operation completes in a single logical step, such as addition of two numbers.
*Compound - Defined as a sequence of multiple atomic operations.
 
Reflection can be used for observing and modifying program execution at [[Runtime (program lifecycle phase)|runtime]]. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal of that enclosure. This is typically accomplished by dynamically assigning program code at runtime.
A compound statement, in classic procedural or object-oriented programming, loses its structure once it is compiled. The reflective paradigm introduces the concept of ''meta-information'', which keeps knowledge of this structure. Meta-information stores information such as the name of the contained methods, name of the class, name of parent classes, or even what the compound statement is supposed to do. This is achieved by keeping information of the change of states that the statement causes the data to go through. So, when a datum (object) is encountered, it can be reflected to find out the operations that it supports, and the one that causes the required state transition can be chosen at run-time, without the need to specify it in code.
 
In [[object-oriented programming]] languages such as [[Java (programming language)|Java]], reflection allows ''inspection'' of classes, interfaces, fields and methods at runtime without knowing the names of the interfaces, fields, methods at [[compile time]]. It also allows ''instantiation'' of new objects and ''invocation'' of methods.
==Uses of reflection==
Reflection can be used for self-optimization or self-modification of a program. A reflective sub-component of a program will monitor the execution of a program and will optimize or modify itself according to the function the program is solving. This is done by modifying the program's own memory area, where the code is stored.
 
Reflection is often used as part of [[software testing]], such as for the runtime creation/instantiation of [[mock object]]s.
Reflection can also be used to adapt a given system dynamically to different situations. Consider, for example, an application that uses some class X to communicate with some service. Now suppose it needed to communicate with a different service, via a different class Y, which has different method names. If the method names were hard coded into the application, it would need to be rewritten, but if it used reflection this could be avoided. Using reflection, the application would have a knowledge about the methods in class X. And class X could be designed to provide information regarding which method is being used for what purpose. The application, depending on what it has to do, would select the required method and use it. Now, when the different service is being used, via class Y, the application would search the methods in the new class to find the required methods and use them. No modification of the code is necessary. Even the class name need not be hard coded, rather it can be stored in a configuration file, it will be correctly searched for and loaded at run time.
 
Reflection is also a key strategy for [[metaprogramming]].
 
In some object-oriented programming languages such as [[C Sharp (programming language)|C#]] and [[Java (programming language)|Java]], reflection can be used to bypass [[member accessibility]] rules. For C#-properties this can be achieved by writing directly onto the (usually invisible) backing field of a non-public property. It is also possible to find non-public methods of classes and types and manually invoke them. This works for project-internal files as well as external libraries such as [[.NET Framework|.NET]]'s assemblies and Java's archives.
 
==Implementation==
{{Unreferenced section|date=January 2008}}
A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure or impossible to accomplish in a lower-level language. Some of these features are the abilities to:
A language that supports reflection provides a number of features available at runtime that would otherwise be difficult to accomplish in a lower-level language. Some of these features are the abilities to:
* Discover and modify [[Source code|source-code]] constructions (such as code blocks, [[Class (computer science)|classes]], methods, protocols, etc.) as [[first-class object]]s at [[Runtime (program lifecycle phase)|runtime]].
* Convert a [[string (computer science)|string]] matching the symbolic name of a class or function into a reference to or invocation of that class or function.
* Evaluate a string as if it were a source-code statement at runtime.
* Create a new [[Interpreter (computing)|interpreter]] for the language's [[bytecode]] to give a new meaning or purpose for a programming construct.
 
These features can be implemented in different ways. In [[MOO (programming language)|MOO]], reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as ''verb'' (the name of the verb being called) and ''this'' (the object on which the verb is called) are populated to give the context of the call. Security is typically managed by accessing the caller stack programmatically: Since ''callers''() is a list of the methods by which the current verb was eventually called, performing tests on ''callers''()[0] (the command invoked by the original user) allows the verb to protect itself against unauthorised use.
*Discover and modify source code constructions (such as code blocks, [[Class (computer science)|class]]es, methods, protocols, etc.) as a [[first-class object]] at runtime.
*Convert a [[string (computer science)|string]] matching the symbolic name of a class or function into a reference to or invocation of that class or function.
*Evaluate a string as if it were a source code statement at runtime.
 
Compiled languages rely on their runtime system to provide information about the source code. A compiled [[Objective-C]] executable, for example, records the names of all methods in a block of the executable, providing a table to correspond these with the underlying methods (or selectors for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as [[Common Lisp]], the runtime environment must include a compiler or an interpreter.
These features can be implemented in different ways. In [[MOO programming language|MOO]], reflection forms a natural part of everyday programming idiom. When verbs (methods) are called, various variables such as ''verb'' (the name of the verb being called) and ''this'' (the object on which the verb is called) are populated to give the context of the call. Security is typically managed by accessing the caller stack programmatically: Since ''callers()'' is a list of the methods by which the current verb was eventually called, performing tests on callers()[1] (the command invoked by the original user) allows the verb to protect itself against unauthorised use.
 
Reflection can be implemented for languages without built-in reflection by using a [[program transformation]] system to define automated source-code changes.
Compiled languages rely on their runtime system to provide information about the source code. A compiled [[Objective-C]] executable, for example, records the names of all methods in a block of the executable, providing a table to correspond these with the underlying methods (or [[selector]]s for these methods) compiled into the program. In a compiled language that supports runtime creation of functions, such as [[Common Lisp]], the runtime environment must include a compiler or an interpreter.
 
==Security considerations==
Reflection can be implemented for languages not having built-in reflection facilities by using a [[program transformation]] system to define automated source code changes..
 
Reflection may allow a user to create unexpected [[control flow]] paths through an application, potentially bypassing security measures. This may be exploited by attackers.<ref>{{cite report |first1=Paulo |last1=Barros |first2=René |last2=Just |first3=Suzanne |last3=Millstein |first4=Paul |last4=Vines |first5=Werner |last5=Dietl |first6=Marcelo |last6=d'Amorim |first7=Michael D. |last7=Ernst |date=August 2015 |title=Static Analysis of Implicit Control Flow: Resolving Java Reflection and Android Intents |url=https://homes.cs.washington.edu/~mernst/pubs/implicit-control-flow-tr150801.pdf |publisher=University of Washington |id=UW-CSE-15-08-01 |access-date=October 7, 2021 }}</ref> Historical [[Vulnerability (computing)|vulnerabilities]] in Java caused by unsafe reflection allowed code retrieved from potentially untrusted remote machines to break out of the Java [[Sandbox (computer security)|sandbox]] security mechanism. A large scale study of 120 Java vulnerabilities in 2013 concluded that unsafe reflection is the most common vulnerability in Java, though not the most exploited.<ref>{{cite magazine |author=Eauvidoum, Ieu |author2=disk noise |date=October 5, 2021 |title=Twenty years of Escaping the Java Sandbox |url=http://phrack.org/issues/70/7.html#article |magazine=[[Phrack]] |volume=10 |issue=46 |access-date=October 7, 2021}}</ref>
 
==Examples==
The following code snippets create an [[instance (computer science)|instance]] {{code|foo}} of [[class (computer science)|class]] {{code|Foo}} and invoke its [[method (computer science)|method]] {{code|PrintHello}}. For each [[programming language]], normal and reflection-based call sequences are shown.
 
=== Common Lisp ===
The following is an example in [[Common Lisp]] using the [[Common Lisp Object System]]:
 
<syntaxhighlight lang="lisp">
(defclass foo () ())
(defmethod print-hello ((f foo)) (format T "Hello from ~S~%" f))
 
;; Normal, without reflection
(let ((foo (make-instance 'foo)))
(print-hello foo))
 
;; With reflection to look up the class named "foo" and the method
;; named "print-hello" that specializes on "foo".
(let* ((foo-class (find-class (read-from-string "foo")))
(print-hello-method (find-method (symbol-function (read-from-string "print-hello"))
nil (list foo-class))))
(funcall (sb-mop:method-generic-function print-hello-method)
(make-instance foo-class)))
</syntaxhighlight>
 
=== C++ ===
The following is an example in [[C++]].
 
<syntaxhighlight lang="cpp">
import std;
 
using std::string_view;
using std::meta::info;
using std::views::filter;
 
class Foo {
private:
// ...
public:
void printHello() const noexcept {
std::println("Hello, world!");
}
};
 
[[nodiscard]]
consteval bool isNonstaticMethod(info mem) noexcept {
return is_class_member(mem)
&& !is_static_member(mem)
&& is_function(mem);
}
 
[[nodiscard]]
consteval info findMethod(info ty, const char* name) {
constexpr auto ctx = std::meta::access_context::current();
for (info member : members_of(ty, ctx) | filter(isNonstaticMethod)) {
if (identifier_of(member) == name) {
return member;
}
}
return info{};
}
 
template <info Ty, auto Name>
constexpr auto createInvokerImpl = []() -> auto {
using Type = [: Ty :];
static constexpr info M = findMethod(Ty, Name);
static_assert(parameters_of(M).size() == 0 && return_type_of(M) == ^^void);
return [](Type& instance) -> void { instance.[: M :](); };
}();
 
[[nodiscard]]
consteval info createInvoker(info ty, string_view name) {
return substitute(^^createInvokerImpl, {
std::meta::reflect_constant(ty),
std::meta::reflect_constant_string(name)});
}
 
int main(int argc, char* argv[]) {
Foo foo;
 
// Without reflection
foo.printHello();
 
// With reflection
auto invokePrint = [: createInvoker(^^Foo, "printHello") :];
invokePrint(foo);
 
return 0;
}
</syntaxhighlight>
 
=== C# ===
The following is an example in [[C Sharp (programming language)|C#]]:
 
<syntaxhighlight lang="c#">
using System;
using System.Reflection;
 
class Foo {
// ...
public void PrintHello() {
Console.WriteLine("Hello, world!");
}
}
 
public class InvokeFooExample {
static void Main(string[] args) {
// Without reflection
Foo foo = new Foo();
foo.PrintHello();
 
// With reflection
Object foo = Activator.CreateInstance("complete.classpath.and.Foo");
MethodInfo method = foo.GetType().GetMethod("PrintHello");
method.Invoke(foo, null);
}
}
</syntaxhighlight>
 
===Delphi, Object Pascal===
This [[Delphi (software)|Delphi]] and [[Object Pascal]] example assumes that a {{mono|TFoo}} class has been declared in a unit called {{mono|Unit1}}:
 
<syntaxhighlight lang="Delphi">
uses RTTI, Unit1;
 
procedure WithoutReflection;
var
Foo: TFoo;
begin
Foo := TFoo.Create;
try
Foo.Hello;
finally
Foo.Free;
end;
end;
 
procedure WithReflection;
var
RttiContext: TRttiContext;
RttiType: TRttiInstanceType;
Foo: TObject;
begin
RttiType := RttiContext.FindType('Unit1.TFoo') as TRttiInstanceType;
Foo := RttiType.GetMethod('Create').Invoke(RttiType.MetaclassType, []).AsObject;
try
RttiType.GetMethod('Hello').Invoke(Foo, []);
finally
Foo.Free;
end;
end;
</syntaxhighlight>
 
===eC===
The following is an example in eC:
 
<syntaxhighlight lang=eC>
// Without reflection
Foo foo { };
foo.hello();
 
// With reflection
Class fooClass = eSystem_FindClass(__thisModule, "Foo");
Instance foo = eInstance_New(fooClass);
Method m = eClass_FindMethod(fooClass, "hello", fooClass.module);
((void (*)())(void *)m.function)(foo);
</syntaxhighlight>
 
===Go===
The following is an example in [[Go (programming language)|Go]]:
 
<syntaxhighlight lang="go">
import "reflect"
 
// Without reflection
f := Foo{}
f.Hello()
 
// With reflection
fT := reflect.TypeOf(Foo{})
fV := reflect.New(fT)
 
m := fV.MethodByName("Hello")
if m.IsValid() {
m.Call(nil)
}
</syntaxhighlight>
 
===Java===
The following is an example in [[Java (programming language)|Java]] using the [[Java package]] {{Javadoc:SE|package=java.lang.reflect|java/lang/reflect}}. Consider two pieces of code
<sourcesyntaxhighlight lang="java">
import java.lang.reflect.Method;
// Without reflection
Foo foo = new Foo();
foo.hello();
 
class Foo {
// With reflection
// ...
Class cls = Class.forName("Foo");
public void printHello() {
Method method = cls.getMethod("hello", null);
System.out.println("Hello, world!");
method.invoke(cls.newInstance(), null);
}
</source>
}
Both code fragments create an instance of a class <code>Foo</code> and call its <code>hello()</code> method. The difference is that, in the first fragment, the names of the class and method are hard-coded; it is not possible to use a class of another name. In the second fragment, the names of the class and method can easily be made to vary at [[runtime]]. The downside is that the second version is harder to read, and is not protected by compile-time syntax and semantic checking. For example, if no class Foo exists, an error will be generated at compile time for the first version. The equivalent error will only be generated at run time for the second version.
 
public class InvokeFooExample {
===PHP===
public static void main(String[] args) {
Here is an equivalent example in [[PHP]]:
// Without reflection
<source lang="php">
Foo foo = new Foo();
# without reflection
foo.printHello();
$Foo = new Foo();
$Foo->hello();
 
# with // With reflection
try {
$class = "Foo";
Foo foo = Foo.class.getDeclaredConstructor().newInstance();
$method = "hello";
$object = new $class();
$object->$method();
</source>
 
Method m = foo.getClass().getDeclaredMethod("printHello", new Class<?>[0]);
===Perl===
m.invoke(foo);
Here is an equivalent example in [[Perl]]:
} catch (ReflectiveOperationException e) {
System.err.printf("An error occurred: %s%n", e.getMessage());
}
}
}
</syntaxhighlight>
 
===JavaScript/TypeScript===
# without reflection
The following is an example in [[JavaScript]]:
my $foo = Foo->new();
$foo->hello();
 
<syntaxhighlight lang="javascript">
# with reflection
// Without reflection
my $class = "Foo";
const foo = new Foo();
my $method = "hello";
foo.hello();
my $object = $class->new();
$object->$method();
 
// With reflection
===Ruby===
const foo = Reflect.construct(Foo);
Here is an equivalent example in [[Ruby (programming language)|Ruby]]:
const hello = Reflect.get(foo, 'hello');
# without reflection
Reflect.apply(hello, foo, []);
Foo.new.hello
 
// With eval
# with reflection
Class.const_geteval("'new Foo"().new.send(:hello()');
</syntaxhighlight>
 
The following is the same example in [[TypeScript]]:
===Windows PowerShell===
Here is an equivalent example in [[Windows PowerShell]]:
 
<syntaxhighlight lang="typescript">
# without reflection
// Without reflection
$foo = new-object Foo
const foo: Foo = new Foo();
$foo.hello()
foo.hello();
# with reflection
$class = 'Foo'
$method = 'hello'
$object = new-object $class
$object.$method.Invoke()
 
// With reflection
===MOO===
const foo: Foo = Reflect.construct(Foo);
Here is an equivalent example in [[MOO programming language |MOO]]:
const hello: (this: Foo) => void = Reflect.get(foo, 'hello') as (this: Foo) => void;
"without reflection";
Reflect.apply(hello, foo, []);
foo:hello();
"with partial reflection";
foo:("hello")();
 
// With eval
===Python===
eval('new Foo().hello()');
Here is an equivalent example in [[Python (programming language)|Python]]:
</syntaxhighlight>
<source lang="python">
# without reflection
Foo().hello()
 
===Julia===
# with reflection
The following is an example in [[Julia (programming language)|Julia]]:
getattr(globals()['Foo'](), 'hello')()
<syntaxhighlight lang="julia-repl">
</source>
julia> struct Point
x::Int
y
end
 
# Inspection with reflection
===Objective-C===
julia> fieldnames(Point)
Here is an equivalent example in [[Objective-C]] (using [[Cocoa (API)|Cocoa]] runtime):
(:x, :y)
 
julia> fieldtypes(Point)
// Without reflection
(Int64, Any)
<nowiki>[[[Foo alloc] init] hello];</nowiki>
 
julia> p = Point(3,4)
// With reflection
Class aClass = NSClassFromString(@"Foo");
SEL aSelector = NSSelectorFromString(@"hello"); // or @selector(hello) if the method
// name is known at compile time
<nowiki>[[[aClass alloc] init] performSelector:aSelector];</nowiki>
 
# Access with reflection
===C++===
julia> getfield(p, :x)
3
</syntaxhighlight>
 
===Objective-C===
Although the language itself does not provide any support for reflection, there are some attempts based on templates, [[RTTI]] information, using debug information provided by the compiler, or even patching the GNU compiler to provide extra information.
The following is an example in [[Objective-C]], implying either the [[OpenStep]] or [[Foundation Kit]] framework is used:
 
<syntaxhighlight lang="ObjC">
===ActionScript===
// Foo class.
Here is an equivalent example in [[ActionScript]]:
@interface Foo : NSObject
- (void)hello;
@end
 
// WithoutSending "hello" to a Foo instance without reflection.
var foo:Foo* obj = new [[Foo() alloc] init];
foo.[obj hello()];
 
// WithSending "hello" to a Foo instance with reflection.
id obj = [[NSClassFromString(@"Foo") alloc] init];
var ClassReference:Class = flash.utils.getDefinitionByName("Foo");
[obj performSelector: @selector(hello)];
var instance:Object = new ClassReference();
</syntaxhighlight>
instance.hello();
 
===Perl===
Even with an import statement on “Foo”, the method call to “getDefinitionByName” will break without an internal reference to the class. The reason for this is because runtime compilation of source is NOT allowable at the current time. Maybe in the future it might, but not now. To get around this, you have to have at least one instantiation of the class type in your code for the above to work. So in your class definition you declare a variable of the custom type you want to use:
The following is an example in [[Perl]]:
 
<syntaxhighlight lang="perl">
var customType : Foo;
# Without reflection
my $foo = Foo->new;
$foo->hello;
 
# or
So for the idea of dynamically creating a set of views in Flex 2 using these methods in conjunction with an xml file that may hold the names of the views you want to use, in order for that to work, you will have to instantiate a variable of each type of view that you want to utilize.
Foo->new->hello;
 
# With reflection
===ECMAScript (JavaScript)===
my $class = "Foo"
Here is an equivalent example in [[ECMAScript]]:
my $constructor = "new";
my $method = "hello";
 
my $f = $class->$constructor;
// Without reflection
$f->$method;
new Foo().hello()
 
# or
// With reflection
$class->$constructor->$method;
// assuming that Foo resides in ''this''
(new this['Foo']()) ['hello']()
// or without assumption
(new (eval('Foo'))()) ['hello']()
 
# with eval
=== Common Lisp ===
eval "new Foo->hello;";
Here is an equivalent example in [[Common Lisp]]:
</syntaxhighlight>
 
===PHP===
;;Without reflection
The following is an example in [[PHP]]:<ref>{{cite web |title=PHP: ReflectionClass - Manual |url=https://www.php.net/manual/en/class.reflectionclass.php |website=www.php.net}}</ref>
(hello)
 
<syntaxhighlight lang="php">
;;With reflection
// Without reflection
(funcall (read-from-string "hello"))
$foo = new Foo();
$foo->hello();
 
// With reflection, using Reflections API
;;or
$reflector = new ReflectionClass("Foo");
(funcall (symbol-function (intern "hello")))
$foo = $reflector->newInstance();
$hello = $reflector->getMethod("hello");
$hello->invoke($foo);
</syntaxhighlight>
 
===Python===
However, this works only for symbols in topmost lexical environment (or dynamic one).
The following is an example in [[Python (programming language)|Python]]:
Better example, using [[CLOS]], is:
;;Method hello is called on instance of class foo.
(hello (make-instance 'foo))
 
<syntaxhighlight lang="python">
;;or
from typing import Any
(hello (make-instance (find-class 'foo))
 
class Foo:
This code is equivalent to Java's one.
# ...
def print_hello() -> None:
print("Hello, world!")
 
if __name__ == "__main__":
=== Scheme ===
# Without reflection
Here is an equivalent example in [[Scheme (programming language)|Scheme]]:
obj: Foo = Foo()
obj.print_hello()
 
; Without # With reflection
obj: Foo = globals()["Foo"]()
(hello)
_: Any = getattr(obj, "print_hello")()
 
; # With reflectioneval
eval("Foo().print_hello()")
(eval '(hello))
</syntaxhighlight>
 
===R===
; With reflection via string using string I/O ports
The following is an example in [[R (programming language)|R]]:
(eval (read (open-input-string "(hello)")))
 
<syntaxhighlight lang="r">
=== Io ===
# Without reflection, assuming foo() returns an S3-type object that has method "hello"
Here is an equivalent example in [[Io (programming language)|Io]]:
obj <- foo()
hello(obj)
 
//# WithoutWith reflection
class_name <- "foo"
hello
generic_having_foo_method <- "hello"
obj <- do.call(class_name, list())
do.call(generic_having_foo_method, alist(obj))
</syntaxhighlight>
 
===Ruby===
// With reflection
The following is an example in [[Ruby (programming language)|Ruby]]:
doString("hello")
 
<syntaxhighlight lang="ruby">
===Smalltalk===
# Without reflection
Here is an equivalent example in [[Smalltalk]]:
obj = Foo.new
obj.hello
 
"Without# With reflection"
obj = Object.const_get("Foo").new
Foo new hello
obj.send :hello
 
"# With reflection"eval
(Compilereval evaluate: '"Foo') .new perform: #.hello"
</syntaxhighlight>
 
===Rust===
The class name and the method name will often be stored in variables and in practice runtime checks need to be made to ensure that it is safe to perform the operations:
[[Rust (programming language)|Rust]] does not have compile-time reflection in the standard library, but it is possible using some third-party libraries such as "[https://docs.rs/bevy_reflect/latest/bevy_reflect/ {{mono|bevy_reflect}}]".
 
<syntaxhighlight lang="rust">
<pre>"With reflection"
use std::any::TypeId;
 
use bevy_reflect::prelude::*;
| x y className methodName |
use bevy_reflect::{
FunctionRegistry,
GetTypeRegistration,
Reflect,
ReflectFunction,
ReflectFunctionRegistry,
ReflectMut,
ReflectRef,
TypeRegistry
};
 
#[derive(Reflect)]
className := 'Foo'.
#[reflect(DoFoo)]
methodName := 'hello'.
struct Foo {
// ...
}
 
impl Foo {
x := (Compiler evaluate: className).
fn new() -> Self {
Foo {}
}
 
fn print_hello(&self) {
(x isKindOf: Class) ifTrue: [
println!("Hello, world!");
y := x new.
}
}
 
#[reflect_trait]
(y respondsTo: methodName asSymbol) ifTrue: [
trait DoFoo {
y perform: methodName asSymbol
fn print_hello(&self);
]
}
]</pre>
 
impl DoFoo for Foo {
Smalltalk also makes use of blocks of compiled code that are passed around as objects. This means that generalised frameworks can be given variations in behavior for them to execute. Blocks allow delayed and conditional execution. They can be parameterised. (Blocks are implemented by the class Context).
fn print_hello(&self) {
self.print_hello();
}
}
 
fn main() {
X := [ :op | 99 perform: op with: 1].
// Without reflection
".....then later we can execute either of:"
let foo: Foo = Foo::new();
X value: #+ "which gives 100, or"
foo.print_hello();
X value: #- "which gives 98."
 
// With reflection
=== Lua ===
let mut registry: TypeRegistry = TypeRegistry::default();
Here's an equivalent example in [[Lua (programming language)|Lua]]:
 
registry.register::<Foo>();
<code>
registry.register_type_data::<Foo, ReflectFunctionRegistry>();
''-- Without reflection''
registry.register_type_data::<Foo, ReflectDoFoo>();
'''hello'''()
</code>
 
let foo: Foo = Foo;
<code>
let reflect_foo: Box<dyn Reflect> = Box::new(foo);
''-- With reflection''
'''loadstring'''("hello()")()
</code>
 
// Version 1: call hello by trait
The function [http://www.lua.org/manual/5.1/manual.html#pdf-loadstring loadstring] compiles the chunk and returns it as a parameterless function.
let trait_registration: &ReflectDoFoo = registry
.get_type_data::<ReflectDoFoo>(TypeId::of::<Foo>())
.expect("ReflectDoFoo not found for Foo");
 
let trait_object: &dyn DoFoo = trait_registration
If '''hello''' is a global function, it can be acessed by using the table [http://www.lua.org/manual/5.1/manual.html#pdf-_G _G]:
.get(&*reflect_foo)
.expect("Failed to get DoFoo trait object");
 
trait_object.print_hello();
<code>
''-- Using the table _G, which holds all global variables''
_G["hello"]()
</code>
 
// Version 2: call hello by function name
===C#===
let func_registry: &FunctionRegistry = registry
Here is an equivalent example in [[C Sharp|C#]]:
.get_type_data::<FunctionRegistry>(TypeId::of::<Foo>())
<source lang="csharp">
.expect("FunctionRegistry not found for Foo");
//Without reflection
Foo foo = new Foo();
foo.Hello();
 
if let Some(dyn_func) = func_registry.get("print_hello") {
//With reflection
let result: Option<Box<dyn Reflect>> = dyn_func
Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo");
.call(&*reflect_foo, Vec::<Box<dyn Reflect>>::new())
t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null);
.ok();
</source>
 
if result.is_none() {
The following example, written in [[C Sharp|C#]], demonstrates the use of advanced features of reflection. The program takes the name of an [[.NET assembly|assembly]] as input from the command-line. An assembly can be thought of as a [[class library]]. The assembly is loaded, and reflection is used to find its methods. For each method, it uses reflection to find whether it was recently modified or not. If it was recently modified, and if it does not require any parameters, the name and return type of the method is displayed.
println!("Function called, no result returned (as expected for void return)");
}
} else {
println!("No function named hello found in FunctionRegistry");
}
}
</syntaxhighlight>
 
===Xojo===
To find whether a method was recently modified or not, the developer needs to use a custom ''attribute'', to define the method as recently modified, and the assembly which contains the class is attributed to be supporting the attribute. The presence of the attribute denotes the method to be recently modified, and its absence denotes it to be old. An attribute is [[metadata]] regarding the program structure, here a [[method (programming)|method]]. An attribute is itself implemented as a class. When using the assembly, the program loads the assembly dynamically at runtime, and checks the assembly for the attribute which says that the assembly supports the attribute which specifies methods as old or recently modified. If it is supported, names of all the methods are then retrieved. For each method, its attributes are retrieved. If the attribute which marks the method as new is present, the list of parameters which the method takes is retrieved. If the list is empty, i.e., the method does not take any arguments, it is printed along with the return type of the method and the comment that the developer might have added to make the attribute, which defines the method to be recent more informatively.
The following is an example using [[Xojo]]:
<source lang="csharp">
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Recent;
namespace Reflect
{
class Program
{
private Assembly a;
Program(String assemblyName)
{
a = Assembly.Load(new AssemblyName(assemblyName));
//Make sure the assembly supports the DateCreated attribute
Attribute c=Attribute.GetCustomAttribute(a, typeof(SupportsRecentlyModifiedAttribute));
if (c == null)
{
//Retrieval of "SupportsRecentlyModified" attribute failed.
//This means that the assembly probably doesn't support it.
throw new Exception(assemblyName + " does not support required attributes");
}
Console.WriteLine("Loaded: " + a.FullName);
}
public void FindNewMethodsWithNoArgs()
{
//Get all types defined in the assembly
Type[] t = a.GetTypes();
foreach (Type type in t)
{
//If this type is not a class, skip it and try the next type
if (!type.IsClass)
continue;
Console.WriteLine("Class: " + type.FullName);
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
object[] b = method.GetCustomAttributes(typeof(RecentlyModifiedAttribute), true);
//If no attribute is retrieved, the method is old.
if (b.Length != 0)
{
//Otherwise, only one attribute will be received, as "RecentlyModified" does
//not support usage with another attribute
Console.Write("\tNew Method: " + method.Name);
//A class representing "RecentlyModifiedAttribute" is instantiated
//from the attribute and it is used to retrieve the comment that
//the developer put in.
ParameterInfo[] pinfo = method.GetParameters();
if (pinfo.Length > 0)
break;
Console.WriteLine("\t" + (b[0] as RecentlyModifiedAttribute).comment);
Console.WriteLine("\t\tReturn type: " + method.ReturnType.Name);
}
}
}
}
static void Main(string[] args)
{
try
{
Program reflector = new Program("UseAttributes");//Console.ReadLine());
reflector.FindNewMethodsWithNoArgs();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
}
}
</source>
The implementation of the custom attributes is shown here.
<source lang="csharp">
using System;
using System.Collections.Generic;
using System.Text;
namespace Recent
{
//Make sure the attribute is applied only to methods
//and that it can not be used with other attributes.
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
public class RecentlyModifiedAttribute : Attribute
{
//The Attribute is expected to be used on methods without any arguments
//(as in [RecentlyModified])
//or with comments (as in [RecentlyModified(comment="<someComment>")])
private String Comment = "This method has recently been modified";
public RecentlyModifiedAttribute()
{
//This is an empty constructor handling instantiation of the attribute
//It is empty because no arguments is necessary for use of the attribute
}
//Optional named argument "comment" has to be supported. So a property "comment" is defined
//specifying how to handle the comment. It has to be used as a named argument when the
//Attribute is being used. This will tell the compiler which property handles the argument.
public String comment
{
get
{
return Comment;
}
set
{
Comment = comment;
}
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
public class SupportsRecentlyModifiedAttribute : Attribute
{
//The attribute is to be used with classes without any arguments
//as in [SupportsRecentlyModified]
public SupportsRecentlyModifiedAttribute()
{
//The constructor is empty because no arguments are required to use the attribute
}
}
}
</source>
And the usage of the custom attributes, defined above, in building a class is shown here.
<source lang="csharp">
using System;
using System.Collections.Generic;
using System.Text;
using Recent;
//Use "SupportsRecentlyModified" attribute to specify that the
//assembly supports the "RecentlyModified" attribute
[assembly: SupportsRecentlyModified]
namespace Reflect
{
class UseAttributes
{
private Object info;
public UseAttributes()
{
info = (object) "Hello World";
}
public void OldMethodWithNoArgs()
{
Console.WriteLine("This is an old method which takes no arguments.");
}
//Use the "RecentlyModified" attribute to specify that the method was recently modified.
[RecentlyModified]
public void NewMethodWithNoArgs()
{
Console.WriteLine("This is a recently modified method that takes no arguments.");
}
public void OldMethodWithOneArg(object something)
{
info = something;
Console.WriteLine("This is an old method that takes one argument.");
}
[RecentlyModified]
public void NewMethodWithOneArg(object something)
{
info = something;
Console.WriteLine("This is a new method that takes one argument.");
}
}
}
</source>
 
<syntaxhighlight lang="vbnet">
' Without reflection
Dim fooInstance As New Foo
fooInstance.PrintHello
 
' With reflection
Dim classInfo As Introspection.Typeinfo = GetTypeInfo(Foo)
Dim constructors() As Introspection.ConstructorInfo = classInfo.GetConstructors
Dim fooInstance As Foo = constructors(0).Invoke
Dim methods() As Introspection.MethodInfo = classInfo.GetMethods
For Each m As Introspection.MethodInfo In methods
If m.Name = "PrintHello" Then
m.Invoke(fooInstance)
End If
Next
</syntaxhighlight>
 
==See also==
* [[List of reflective programming languages and platforms]]
*[[Type introspection]]
* [[Mirror (programming)]]
*[[Self-modifying code]]
* [[Programming paradigm]]s
* [[Self-hosting (compilers)]]
*[[List of reflective programming languages and platforms]]
* [[Self-modifying code]]
* [[Type introspection]]
* [[typeof]]
 
== References ==
=== Citations ===
*[http://www.cs.indiana.edu/~jsobel/rop.html Reflection-oriented programming]
{{Reflist}}
 
==External= linksSources ===
{{refbegin}}
*[http://citeseer.ist.psu.edu/106401.html Reflection in logic, functional and object-oriented programming: a Short Comparative Study] ([[Citeseer]] page).
* Jonathan M. Sobel and Daniel P. Friedman. [https://web.archive.org/web/20100204091328/http://www.cs.indiana.edu/~jsobel/rop.html ''An Introduction to Reflection-Oriented Programming''] (1996), [[Indiana University]].
* [httphttps://msdn2www.microsoftcodeproject.com/en-usArticles/library674455/y0114hz2(VS.80).aspxAnti-Reflector-NET-Code-Protection Anti-Reflection intechnique using C# and C++/CLI forwrapper .Netto prevent code thief]
{{refend}}
*[http://www.garret.ru/~knizhnik/cppreflection/docs/reflect.html Reflection for C++]
*[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1751.html Aspects of Reflection in C++]
*[http://www.codeproject.com/library/libreflection.asp LibReflection:] A reflection library for C++.
*[http://sourceforge.net/projects/cppreflect/ A library to provide full reflection for C++ through template metaprogramming techniques.]
*[http://sourceforge.net/projects/crd A c++ reflection-based data dictionary]
 
==Further reading==
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), {{ISBN 1932394184|1-932394-18-4}}
* Ira R. Forman and Scott Danforth, ''Putting Metaclasses to Work'' (1999), {{ISBN |0-201-43305-2}}
 
==External links==
{{Programming language}}
* [https://www-master.ufr-info-p6.jussieu.fr/2007/Ajouts/Master_esj20_2007_2008/IMG/pdf/malenfant-ijcai95.pdf Reflection in logic, functional and object-oriented programming: a short comparative study]
[[Category:Programming paradigms]]
* [https://web.archive.org/web/20100204091328/http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]
* [http://www.laputan.org/#Reflection Brian Foote's pages on Reflection in Smalltalk]
* [http://docs.oracle.com/javase/tutorial/reflect/index.html Java Reflection API Tutorial] from Oracle
{{Programming paradigms navbox}}
{{Types of programming languages}}
 
{{DEFAULTSORT:Reflection (Computer Programming)}}
[[ca:Reflexió (Informàtica)]]
[[Category:Programming constructs]]
[[de:Reflexion (Programmierung)]]
[[Category:Programming language comparisons]]
[[es:Reflexión (informática)]]
<!-- Hidden categories below -->
[[fr:Réflexion (informatique)]]
[[Category:Articles with example BASIC code]]
[[ko:반영 (컴퓨터)]]
[[Category:Articles with example C code]]
[[it:Riflessione (informatica)]]
[[Category:Articles with example C Sharp code]]
[[lt:Refleksija (programavimas)]]
[[Category:Articles with example Java code]]
[[ja:リフレクション (情報工学)]]
[[Category:Articles with example JavaScript code]]
[[pl:Mechanizm refleksji]]
[[Category:Articles with example Julia code]]
[[pt:Reflexão (programação)]]
[[Category:Articles with example Lisp (programming language) code]]
[[ru:Отражение (программирование)]]
[[Category:Articles with example Objective-C code]]
[[vi:Reflection (khoa học máy tính)]]
[[Category:Articles with example Pascal code]]
[[zh:反射 (计算机科学)]]
[[Category:Articles with example Perl code]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example R code]]
[[Category:Articles with example Ruby code]]