FACTOID # 4: Just 1% of the houses in Nevada were built before 1939.
 
 Home   Encyclopedia   Statistics   States A-Z   Flags   Maps   FAQ   About 
   
 
WHAT'S NEW
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Reflection (computer science)

In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. Image File history File links Question_book-3. ... Computer science, or computing science, is the study of the theoretical foundations of information and computation and their implementation and application in computer systems. ... A computer program is a collection of instructions that describe a task, or set of tasks, to be carried out by a computer. ...


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' is 'processed', however, the program can also treat instructions as data and therefore make reflective modifications. Reflection is most common in high-level virtual machine programming languages like Smalltalk, and less common in lower-level programming languages like C. For other uses, see Small talk. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ...


Common types of reflection are runtime and dynamic, but some programming languages support compile time or static reflection. In computer science, compile time, as opposed to runtime, is the time when a compiler compiles code written in a programming language into an executable form. ... Look up static in Wiktionary, the free dictionary. ...

Contents

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 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. In computer science, imperative programming, as opposed to declarative programming, is a programming paradigm that describes computation in terms of a program state and statements that change the program state. ...


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.

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. Metadata is data about data. ...


Uses

Reflection can be used for observing and/or 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.


Reflection can also be used to adapt a given program to different situations dynamically. For example, consider an application that uses two different classes X and Y interchangeably to perform similar operations. Without reflection-oriented programming, the application might be hard-coded to call method names of class X and class Y. However, using the reflection-oriented programming paradigm, the application could be designed and written to utilize reflection in order to invoke methods in classes X and Y without hard-coding method names. Reflection-oriented programming almost always requires additional knowledge, framework, relational mapping, and object relevance in order to take advantage of more generic code execution. Hard-coding can be avoided to the extent that reflection-oriented programming is used.


Reflection is also a key strategy for metaprogramming. Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data or that do part of the work during compile time that is otherwise done at run time. ...


Implementation

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:

  • Discover and modify source code constructions (such as code blocks, classes, methods, protocols, etc.) as a first-class object 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.

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()[1] (the command invoked by the original user) allows the verb to protect itself against unauthorised use. In object-oriented programming, a class is a programming language construct used to group related fields and methods. ... In computing, a first-class object (also value, entity, and citizen), in the context of a particular programming language, is an entity which can be used in programs without restriction (when compared to other kinds of objects in the same language). ... In computer programming and formal language theory, (and other branches of mathematics), a string is an ordered sequence of symbols. ... The MOO programming language is a programming language used to support the MOO system. ...


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. Objective-C, often referred to as ObjC or more seldomly as Objective C or Obj-C, is an object oriented programming language implemented as an extension to C. It is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard, and is the primary language... A selector can be: a Reggae DJ (who selects music to play). ... Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard X3. ...


Reflection can be implemented for languages not having built-in reflection facilities by using a program transformation system to define automated source code changes.. ÁInsert non-formatted text here ...


Examples

ActionScript

Here is an equivalent example in ActionScript: ActionScript is a scripting language based on ECMAScript, used primarily for the development of websites and software using the Adobe Flash Player platform (in the form of SWF files embedded into Web pages). ...

 // Without reflection var foo:Foo = new Foo(); foo.hello(); // With reflection var ClassReference:Class = flash.utils.getDefinitionByName("Foo") as Class; var instance:Object = new ClassReference(); instance.hello(); 

Even with an import statement on “Foo”, the method call to “getDefinitionByName” will break without an internal reference to the class. This is because runtime compilation of source is not currently supported. 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:

 var customType : Foo; 

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.


C#

Here is an equivalent example in C#: The title given to this article is incorrect due to technical limitations. ...

 //Without reflection Foo foo = new Foo(); foo.Hello(); //With reflection Type t = Assembly.GetCallingAssembly().GetType("FooNamespace.Foo"); t.InvokeMember("Hello", BindingFlags.InvokeMethod, null, Activator.CreateInstance(t), null); 

The following example, written in C#, demonstrates the use of advanced features of reflection. It loads an assembly (which can be thought of as a class library) dynamically and uses reflection to find the methods that take no parameters and figure out whether it was recently modified or not. To decide whether a method was recently modified or not, it uses a custom attribute RecentlyModified which the developer tags the methods with. Presence of the attribute indicates it was recently modified. An attribute is itself implemented as a class, that derives from the Attribute class. The title given to this article is incorrect due to technical limitations. ... For the counterpart to assembly language in the Microsoft . ... Illustration of an application which may use libvorbisfile. ... . ...


The program loads the assembly dynamically at runtime, and checks that the assembly supports the RecentlyModified attribute. This check is facilitated by using another custom attribute on the entire assembly: SupportsRecentlyModified. If it is supported, names of all the methods are then retrieved. For each method, objects representing all its parameters as well as the objects representing the RecentlyAttribute are retrieved. If the attribute retrieval succeeds and the parameter retrieval fails (indicating presence of the attribute but absence of any parameters), a match has been found. An object is fundamental concept in object-oriented programming. ... An object is fundamental concept in object-oriented programming. ...

Definition of the custom attributes
 //RecentlyModified: Applicable only to methods.  //SupportsRecentlyModified: Applicable to the entire assembly. [AttributeUsage(AttributeTargets.Method, AllowMultiple=false)] class RecentlyModifiedAttribute : Attribute { public RecentlyModifiedAttribute() { } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)] class SupportsRecentlyModifiedAttribute : Attribute { public SupportsRecentlyModifiedAttribute() { } } 
Implementation of the method filter
 static void Main(string[] args) { //Load the assembly dynamically and make sure it supports the Recently Modified Attribute Assembly loadedAssembly = Assembly.LoadAssembly(Console.ReadLine()); if (Attribute.GetCustomAttribute( loadedAssembly, typeof(SupportsRecentlyModifiedAttribute)) != null) //For each class in the assembly, get all the methods. Iterate through the methods //and find the ones that have both the RecentlyModified attribute set as well as do //not require any arguments. foreach (Type t in loadedAssembly.GetTypes()) { if (t.IsClass) foreach (MethodInfo method in t.GetMethods()) { //Try to retrieve the RecentlyModified attribute object[] rmAttribute = method.GetCustomAttributes( typeof(RecentlyModifiedAttribute), false); //Try to retrieve the parameters ParameterInfo[] parames = method.GetParameters(); if (rmAttribute.Length == 1 && parames.Length == 0) Console.WriteLine("{0}", method.Name); } } } 

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. This article or section should be merged with datatype or runtime. ...


Common Lisp

Here is an equivalent example in Common Lisp: Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard X3. ...

 ;;Without reflection (hello) ;;With reflection (funcall (read-from-string "hello")) ;;or (funcall (symbol-function (intern "hello"))) 

However, this works only for symbols in topmost lexical environment (or dynamic one). A better example, using CLOS, is: The Common Lisp Object System, a powerful system for object-oriented programming which forms part of Common Lisp. ...

 ;;Method hello is called on instance of class foo. (hello (make-instance 'foo)) ;;or (hello (make-instance (find-class 'foo)) 

This code is equivalent to Java's one. Common Lisp, like Scheme, is able to transform lists into functions or procedures. This is the source of the Lisp macro ability to change the code behavior (including from other macros) during (and after) compilation.


Curl

Here is an equivalent example in Curl: Wikibooks has more about this subject: Curl The Curl programming language (unrelated to cURL) is a reflective programming language designed to create interactive web content. ...

 || Without reflection let foo1:Foo = {Foo} {foo1.hello} || Using runtime 'any' calls let foo2:any = {Foo} {foo2.hello} || Using reflection let foo3:any = {Foo} {type-switch {type-of foo3} case class:ClassType do {if-non-null method = {class.get-method "hello"} then {method.invoke foo3} } } 

All three of these examples instantiate an instance of the 'Foo' class and invoke its 'hello' method. The first, resolves the lookup at compile-time and will generate the most efficient code for invoking the method at runtime. The second, invokes the method through an 'any' variable which will do both the lookup and invocation at runtime, which is much less efficient. The third, uses the reflection interface to lookup the method in the 'Foo' class and invoke it, which is also much less efficient than the first example.


ECMAScript (JavaScript)

Here is an equivalent example in ECMAScript: ECMAScript is a scripting programming language, standardized by Ecma International in the ECMA-262 specification. ...

 // Without reflection new Foo().hello() // With reflection // assuming that Foo resides in this new this['Foo']()['hello']() // or without assumption new (eval('Foo'))()['hello']() 

Io

Here is an equivalent example in Io: Io is a pure object-oriented programming language inspired by Smalltalk, Self, Lisp and NewtonScript. ...

 // Without reflection hello 
// With reflection doString("hello")

Java

The following is an example in Java using the Java package java.lang.reflect. Consider two pieces of code Java language redirects here. ... A Java package is a Java programming language mechanism for organizing classes into namespaces. ...

 // Without reflection Foo foo = new Foo(); foo.hello(); // With reflection Class cls = Class.forName("Foo"); Method method = cls.getMethod("hello", null); method.invoke(cls.newInstance(), null); 

Both code fragments create an instance of a class Foo and call its hello() 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. In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination (compare compile time). ...


Lua

Here's an equivalent example in Lua: In computing, the Lua (pronounced LOO-ah) programming language is a lightweight, reflective, imperative and procedural language, designed as a scripting language with extensible semantics as a primary goal. ...

 -- Without reflection hello() 
-- With reflection loadstring("hello()")()

The function loadstring compiles the chunk and returns it as a parameterless function.


If hello is a global function, it can be accessed by using the table _G:

 -- Using the table _G, which holds all global variables _G["hello"]()  

MOO

Here is an equivalent example in MOO: The MOO programming language is a programming language used to support the MOO system. ...

 "without reflection"; foo:hello(); "with partial reflection"; foo:("hello")(); 

Objective-C

Here is an equivalent example in Objective-C (using Cocoa runtime): Objective-C, often referred to as ObjC or more seldomly as Objective C or Obj-C, is an object oriented programming language implemented as an extension to C. It is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard, and is the primary language... A Cocoa application being developed using Xcode. ...

 // Without reflection [[[Foo alloc] init] hello]; // With reflection Class aClass = NSClassFromString(@"Foo"); SEL aSelector = NSSelectorFromString(@"hello"); // or @selector(hello) if the method // name is known at compile time [[[aClass alloc] init] performSelector:aSelector]; 

Perl

Here is an equivalent example in Perl: For other uses, see Perl (disambiguation). ...

 # without reflection my $foo = Foo->new(); $foo->hello(); # with reflection my $class = "Foo"; my $method = "hello"; my $object = $class->new(); $object->$method(); 

PHP

Here is an equivalent example in PHP: For other uses, see PHP (disambiguation). ...

 # without reflection $Foo = new Foo(); $Foo->hello(); # with reflection $class = "Foo"; $method = "hello"; $object = new $class(); $object->$method(); 

Python

Here is an equivalent example from the Python shell with two ways of doing reflection: Python is a general-purpose, high-level programming language. ...

 >>> # Class definition >>> class Foo(object): ... def Hello(self): ... print "Hi" ... >>> # Instantiation >>> foo = Foo() >>> # Normal call >>> foo.Hello() Hi >>> # Evaluate a string in the context of the global namespace >>> eval("foo.Hello()", globals()) Hi >>> # Interpret distinct instance & method names from strings >>> instance = 'foo' >>> method = 'Hello' >>> getattr(globals()[instance], method)() Hi 

REBOL

Here is an example in REBOL: REBOL, the Relative Expression Based Object Language (pronounced [rebl]), is a data exchange and programming language designed specifically for network communications and distributed computing. ...

 ; Without reflection hello 
; With reflection do [hello]

This works because the language is fundamentally reflective, processing via symbols, not strings.


To illustrate that the above example is reflective (not simply evaluation of a code block) you can write:

 if 'hello = first [hello] [print "this is true"] 

Ruby

Here is an equivalent example in Ruby: Ruby is a reflective, dynamic, object-oriented programming language. ...

 # without reflection Foo.new.hello # with reflection Class.const_get(:Foo).new.send(:hello) 

Scheme

Here is an equivalent example in Scheme: Scheme is a multi-paradigm programming language. ...

 ; Without reflection (hello) ; With reflection (eval '(hello)) ; With reflection via string using string I/O ports (eval (read (open-input-string "(hello)"))) 

Smalltalk

Here is an equivalent example in Smalltalk: For other uses, see Small talk. ...

 "Without reflection" Foo new hello "With reflection" (Compiler evaluate: 'Foo') new perform: #hello 

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:

 "With reflection" | x y className methodName | className := 'Foo'. methodName := 'hello'. x := (Compiler evaluate: className). (x isKindOf: Class) ifTrue: [ y := x new. (y respondsTo: methodName asSymbol) ifTrue: [ y perform: methodName asSymbol ] ] 

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 BlockClosure).

 X := [ :op | 99 perform: op with: 1]. ".....then later we can execute either of:" X value: #+ "which gives 100, or" X value: #- "which gives 98." 

Windows PowerShell

Here is an equivalent example in Windows PowerShell: Windows PowerShell is an administration focused extensible command line interface (CLI) shell and scripting language product developed by Microsoft. ...

 # without reflection $foo = new-object Foo $foo.hello() # with reflection $class = 'Foo' $method = 'hello' $object = new-object $class $object.$method.Invoke() 

See also

In computing, type introspection is a capability of some object-oriented programming languages to determine the type of an object at runtime. ... In computer science, self-modifying code is code that alters its own instructions, whether or not it is on purpose, while it is executing. ... A programming paradigm is a paradigmatic style of programming (compare with a methodology, which is a paradigmatic style of doing software engineering). ... Programming languages and platforms that typically support reflection include dynamically typed languages such as Objective-C and Smalltalk; scripting languages such as Perl, PHP, Python, VBScript, and JavaScript; and the Maude system of rewriting logic. ...

References

Further reading

  • Ira R. Forman and Nate Forman, Java Reflection in Action (2005), ISBN 1932394184
  • Ira R. Forman and Scott Danforth, Putting Metaclasses to Work (1999), ISBN 0-201-43305-2

External links

CiteSeer is a public search engine and digital library for scientific and academic papers. ... A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... Array programming languages (also known as vector or multidimensional languages) generalize operations on scalars to apply transparently to vectors, matrices, and higher dimensional arrays. ... An assembly language is a low-level language for programming computers. ... A compiled language is a programming language whose implementations are typically compilers (translators which generate machine code from source code), and not interpreters (step-by-step executors of source code, where no translation takes place). ... Concurrent computing is the concurrent (simultaneous) execution of multiple interacting computational tasks. ... Curly brace or bracket programming languages are those which use balanced brackets ({ and }, also known as brace brackets or simply braces) to make blocks in their syntax or formal grammar, mainly due to being C-influenced. ... A Data-structured language is a programming language in which the data structure is a main organizing principle, representation, model, for data and logic (code) alike, in which both are stored and operated upon, i. ... In computer programming, dataflow programming implements dataflow principles and architecture, and models a program, conceptually if not physically, as a directed graph of the data flowing between operations. ... In computer science, a declarative programming language is a high-level language that describes a problem rather than defining a solution — it makes use of declarative programming. ... A domain-specific programming language (domain-specific language, DSL) is a programming language designed to be useful for a specific set of tasks. ... An esoteric programming language (sometimes shortened to esolang[1]) is a programming language designed as a test of the boundaries of computer programming language design, as a proof of concept, or as a joke. ... Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. ... In computer science, imperative programming, as opposed to declarative programming, is a programming paradigm that describes computation in terms of a program state and statements that change the program state. ... In computer programming, an interpreted language is a programming language whose programs may be executed from source form, by an interpreter. ... Logic programming (which might better be called logical programming by analogy with mathematical programming and linear programming) is, in its broadest sense, the use of mathematical logic for computer programming. ... Machine code or machine language is a system of instructions and data directly executed by a computers central processing unit. ... For other uses, see Macro (disambiguation) A macro in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to an output sequence (also often a sequence of characters) according to a defined procedure. ... Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data or that do part of the work during compile time that is otherwise done at run time. ... This does not cite any references or sources. ... Non-English-based programming languages are computer programming languages that, unlike most well-known programming languages, do not use keywords taken from, or inspired by, the English vocabulary. ... An object-oriented programming language (also called an OO language) is one that allows or encourages, to some degree, object-oriented programming techniques such as encapsulation, inheritance, interfaces, and polymorphism. ... A computer programming language is said to adhere to the off-side rule if in it the scope of declarations (a statement block) is expressed by their indentation, i. ... This article is about the computer programming paradigm. ... Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. ... A scripting language, script language or extension language, is a programming language that controls software application. ... A synchronous programming language is a programming language optimized for programming reactive systems, systems that are often interrupted and must respond quickly. ... Visual Programming in Mindscript A Visual programming language (VPL) is any programming language that lets users specify programs by manipulating program elements graphically rather than by specifying them textually. ...

  Results from FactBites:
 
Computer Science at Millersville University (464 words)
The Department of Computer Science maintains a strong, rigorous, state-of-the-art program in computer science with seven full-time faculty and about 300 majors.
At the Bachelor of Science level, you can prepare for either graduate study and research in computer science, or positions in business, industry, or government.
Millersville University began teaching programming courses in 1963 and the Computer Science degree was approved in 1975.
  More results at FactBites »

 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m