Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Reflective programming
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Ability of a process to examine and modify itself}} {{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> ==Historical background== 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> ==Uses== 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. 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. 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. 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. Reflection is often used as part of [[software testing]], such as for the runtime creation/instantiation of [[mock object]]s. 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 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. 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. Reflection can be implemented for languages without built-in reflection by using a [[program transformation]] system to define automated source-code changes. ==Security considerations== 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 Sharp (programming language)|C#]]: <syntaxhighlight lang="c#"> // Without reflection var 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]]: <syntaxhighlight lang="java"> import java.lang.reflect.Method; // Without reflection Foo foo = new Foo(); foo.hello(); // With reflection try { Object foo = Foo.class.getDeclaredConstructor().newInstance(); Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]); m.invoke(foo); } catch (ReflectiveOperationException ignored) {} </syntaxhighlight> ===JavaScript=== The following is an example in [[JavaScript]]: <syntaxhighlight lang="javascript"> // Without reflection const foo = new Foo() foo.hello() // With reflection const foo = Reflect.construct(Foo) const hello = Reflect.get(foo, 'hello') Reflect.apply(hello, foo, []) // With eval eval('new Foo().hello()') </syntaxhighlight> ===Julia=== The following is an example in [[Julia (programming language)|Julia]]: <syntaxhighlight lang="julia-repl"> julia> struct Point x::Int y end # Inspection with reflection julia> fieldnames(Point) (:x, :y) julia> fieldtypes(Point) (Int64, Any) julia> p = Point(3,4) # Access with reflection julia> getfield(p, :x) 3 </syntaxhighlight> ===Objective-C=== The following is an example in [[Objective-C]], implying either the [[OpenStep]] or [[Foundation Kit]] framework is used: <syntaxhighlight lang="ObjC"> // Foo class. @interface Foo : NSObject - (void)hello; @end // Sending "hello" to a Foo instance without reflection. Foo *obj = [[Foo alloc] init]; [obj hello]; // Sending "hello" to a Foo instance with reflection. id obj = [[NSClassFromString(@"Foo") alloc] init]; [obj performSelector: @selector(hello)]; </syntaxhighlight> ===Perl=== The following is an example in [[Perl]]: <syntaxhighlight lang="perl"> # Without reflection my $foo = Foo->new; $foo->hello; # or Foo->new->hello; # With reflection my $class = "Foo" my $constructor = "new"; my $method = "hello"; my $f = $class->$constructor; $f->$method; # or $class->$constructor->$method; # with eval eval "new Foo->hello;"; </syntaxhighlight> ===PHP=== 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> <syntaxhighlight lang="php"> // Without reflection $foo = new Foo(); $foo->hello(); // With reflection, using Reflections API $reflector = new ReflectionClass("Foo"); $foo = $reflector->newInstance(); $hello = $reflector->getMethod("hello"); $hello->invoke($foo); </syntaxhighlight> ===Python=== The following is an example in [[Python (programming language)|Python]]: <syntaxhighlight lang="python"> # Without reflection obj = Foo() obj.hello() # With reflection obj = globals()["Foo"]() getattr(obj, "hello")() # With eval eval("Foo().hello()") </syntaxhighlight> ===R=== The following is an example in [[R (programming language)|R]]: <syntaxhighlight lang="r"> # Without reflection, assuming foo() returns an S3-type object that has method "hello" obj <- foo() hello(obj) # With reflection class_name <- "foo" generic_having_foo_method <- "hello" obj <- do.call(class_name, list()) do.call(generic_having_foo_method, alist(obj)) </syntaxhighlight> ===Ruby=== The following is an example in [[Ruby (programming language)|Ruby]]: <syntaxhighlight lang="ruby"> # Without reflection obj = Foo.new obj.hello # With reflection obj = Object.const_get("Foo").new obj.send :hello # With eval eval "Foo.new.hello" </syntaxhighlight> ===Xojo=== The following is an example using [[Xojo]]: <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]] * [[Mirror (programming)]] * [[Programming paradigm]]s * [[Self-hosting (compilers)]] * [[Self-modifying code]] * [[Type introspection]] * [[typeof]] == References == === Citations === {{Reflist}} === Sources === {{refbegin}} * 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]]. * [https://www.codeproject.com/Articles/674455/Anti-Reflector-NET-Code-Protection Anti-Reflection technique using C# and C++/CLI wrapper to prevent code thief] {{refend}} ==Further reading== * Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), {{ISBN|1-932394-18-4}} * Ira R. Forman and Scott Danforth, ''Putting Metaclasses to Work'' (1999), {{ISBN|0-201-43305-2}} ==External links== * [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] * [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)}} [[Category:Programming constructs]] [[Category:Programming language comparisons]] <!-- Hidden categories below --> [[Category:Articles with example BASIC code]] [[Category:Articles with example C code]] [[Category:Articles with example C Sharp code]] [[Category:Articles with example Java code]] [[Category:Articles with example JavaScript code]] [[Category:Articles with example Julia code]] [[Category:Articles with example Lisp (programming language) code]] [[Category:Articles with example Objective-C code]] [[Category:Articles with example Pascal code]] [[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]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Ambox
(
edit
)
Template:Citation
(
edit
)
Template:Citation needed
(
edit
)
Template:Cite magazine
(
edit
)
Template:Cite report
(
edit
)
Template:Cite web
(
edit
)
Template:Code
(
edit
)
Template:Distinguish
(
edit
)
Template:ISBN
(
edit
)
Template:Mono
(
edit
)
Template:Programming paradigms navbox
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Types of programming languages
(
edit
)
Template:Unreferenced
(
edit
)
Template:Unreferenced section
(
edit
)
Template:Webarchive
(
edit
)