Submitted Successfully!
To reward your contribution, here is a gift for you: A free trial for our video production service.
Thank you for your contribution! You can also upload a video entry or images related to this topic.
Version Summary Created by Modification Content Size Created at Operation
1 handwiki -- 1394 2022-10-11 01:39:46

Video Upload Options

We provide professional Video Production Services to translate complex research into visually appealing presentations. Would you like to try it?

Confirm

Are you sure to Delete?
Cite
If you have any further questions, please contact Encyclopedia Editorial Office.
HandWiki. Reflection (Computer Programming). Encyclopedia. Available online: https://encyclopedia.pub/entry/28855 (accessed on 16 November 2024).
HandWiki. Reflection (Computer Programming). Encyclopedia. Available at: https://encyclopedia.pub/entry/28855. Accessed November 16, 2024.
HandWiki. "Reflection (Computer Programming)" Encyclopedia, https://encyclopedia.pub/entry/28855 (accessed November 16, 2024).
HandWiki. (2022, October 11). Reflection (Computer Programming). In Encyclopedia. https://encyclopedia.pub/entry/28855
HandWiki. "Reflection (Computer Programming)." Encyclopedia. Web. 11 October, 2022.
Reflection (Computer Programming)
Edit

In computer science, reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.

reflection

1. Historical Background

The earliest computers were programmed in their native assembly language, which were inherently reflective, as these original architectures could be programmed by defining instructions as data and using self-modifying code. As programming moved to compiled higher-level languages such as Algol, Cobol, and Fortran (but also Pascal and C and many other languages), this reflective ability largely disappeared until programming languages with reflection built into their type systems appeared.

Brian Cantwell Smith's 1982 doctoral dissertation[1][2] introduced the notion of computational reflection in procedural programming languages and the notion of the meta-circular interpreter as a component of 3-Lisp.

2. Uses

Reflection helps programmers make generic software libraries to display data, process different formats of data, perform serialization or 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 to operate well in networks by enabling libraries for serialization, bundling and varying data formats. Languages without reflection (e.g. C) have to use auxiliary compilers, e.g. for Abstract Syntax Notation, to produce code for serialization and bundling.

Reflection can be used for observing and modifying program execution at runtime. A reflection-oriented program component can monitor the execution of an enclosure of code and can modify itself according to a desired goal related to that enclosure. This is typically accomplished by dynamically assigning program code at runtime.

In object-oriented programming languages such as 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 objects.

Reflection is also a key strategy for metaprogramming.

In some object-oriented programming languages, such as C# and 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 (.Net-assemblies and Java-archives).

3. Implementation

A language supporting 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 constructions (such as code blocks, classes, methods, protocols, etc.) as first-class objects at runtime.
  • Convert a 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 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, 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 not having built-in reflection facilities by using a program transformation system to define automated source-code changes.

4. Examples

The following code snippets create an instance foo of class Foo and invoke its method PrintHello. For each programming language, normal and reflection-based call sequences are shown.

4.1. C#

The following is an example in C#:

// 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);

4.2. Delphi

This Delphi example assumes that a TFoo class has been declared in a unit called Unit1:

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;

4.3. eC

The following is an example in 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);

4.4. ECMAScript

The following is an example in ECMAScript, and therefore also applies to JavaScript and ActionScript:

// Without reflection new Foo().hello() // With reflection // assuming that Foo resides in this new this['Foo']()['hello']() // or without assumption new (eval('Foo'))()['hello']() // or simply eval('new Foo().hello()') // Using ECMAScript 2015's new Reflect class: Reflect.construct(Foo, [])['hello']()

4.5. Go

The following is an example in 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) }

4.6. Java

The following is an example in Java:

import java.lang.reflect.Method; // Without reflection Foo foo = new Foo(); foo.hello(); // With reflection try { // Alternatively: Object foo = Foo.class.newInstance(); Object foo = Class.forName("complete.classpath.and.Foo").newInstance(); Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]); m.invoke(foo); } catch (Exception e) { // Catching ClassNotFoundException, NoSuchMethodException // InstantiationException, IllegalAccessException }

4.7. Objective-C

The following is an example in Objective-C, implying either the OpenStep or Foundation Kit framework is used:

// 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)];

4.8. Perl

The following is an example in 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;";

4.9. PHP

The following is an example in 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);

4.10. Python

The following is an example in Python:

# Without reflection obj = Foo() obj.hello() # With reflection obj = globals()['Foo']() getattr(obj, 'hello')() # With eval eval('Foo().hello()')

4.11. R

The following is an example in R:

# Without reflection, assuming foo() returns an S3-type object that has method "hello" obj <- foo() hello(obj) # With reflection the.class <- "foo" the.method <- "hello" obj <- do.call(the.class, list()) do.call(the.method, alist(obj))

4.12. Ruby

The following is an example in Ruby:

# Without reflection obj = Foo.new obj.hello # With reflection class_name = "Foo" method_name = :hello obj = Object.const_get(class_name).new obj.send method_name # With eval eval "Foo.new.hello"

4.13. Xojo

The following is an example using Xojo:

' 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

References

  1. Brian Cantwell Smith, Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD dissertation, 1982. http://hdl.handle.net/1721.1/15961
  2. Brian C. Smith. Reflection and semantics in a procedural language . Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Massachusetts, January 1982. http://publications.csail.mit.edu/lcs/specpub.php?id=840
More
Information
Contributor MDPI registered users' name will be linked to their SciProfiles pages. To register with us, please refer to https://encyclopedia.pub/register :
View Times: 1.5K
Entry Collection: HandWiki
Revision: 1 time (View History)
Update Date: 11 Oct 2022
1000/1000
ScholarVision Creations