CSC/ECE 517 Fall 2012/ch1b 1w40 ar

From PG_Wiki
Jump to: navigation, search



By looking at the mirror, we can see our image and we can act on what we see like straightening the tie. In Software programming, Reflection is a feature of some programming languages and scripting languages that allows them to change their own structure at run-time. For example in high level object oriented languages the ability to inspect its class interfaces and methods at run time without knowing their names at compile time. It provides the ability to modify, instantiate and access to methods such as getter's and setter's of a class. Since the program need not have all the information at compile time it makes the program more dynamic.


The earliest computers were programmed in their native assembly language , which is inherently reflective as it is programmed by defining the instructions as data. Reflective functionality such as modifying the instructions or analyzing them was commonplace. As programming moved to higher level languages such as C, this practice disappeared until programming languages with reflection in their type system appeared. Brian Cantwell Smith's 1982 doctoral dissertation[1][2] introduced the notion of computational reflection in programming languages, and the notion of the meta-circular interpreter as a component of 3-Lisp[3].

Types of reflection

There are two basic types of reflection. They are:

Behavioral Reflection

Behavioral refection is the ability to intercept an operation such as method invocation and alter the behavior of that operation. If an operation is intercepted, the run-time system calls a method on a meta-object for notifying it of that event. The developers can define their own version of the meta-object so that the meta-object can execute the intercepted operation with customized semantics.[4]. Behavioral reflection focuses on the application’s computational semantics. For instance, a distributed application can use behavioral reflection to select and load a communication protocol well suited to current network conditions [5].However, behavioral refection only provides the ability to alter the behavior of operation and does not provide the ability to alter data structures used by the program statically fixed at compile time.

Structural Reflection

This type of reflection deals with changing the very structure of the program such as the data structures and flow of control in the program [6]. Structural reflection addresses issues related to class hierarchy, object interconnection, and data types. As an example, a metalevel object can examine a baselevel object to determine what methods are available for invocation.


There are many challenges faced by designers of reflective languages. They must provide as much leeway as possible for late binding and at the same time they must optimize the compilation of the static components so that they are ready for run-time. Reflection is in essence a connection between the object-level (program) and meta-level (the processor). The ability of the object level to be able to observe and modify the meta-level information is the consequence of this connection. These actions can be termed as introspection.(This involves the action of observing the class) and intercession (this involves the operation of modifying the behavior of the class). These actions can implemented with of the following components:

Common languages that exhibit reflection to varying degrees are Ruby, Java, Smalltalk, C# and more. We have primarily focused on Java and C# as these are widely used object oriented languages.


Ruby Reflection allows program entities to discover things about themselves through introspection. For example, an object can ask what its methods are, and a class can tell what its ancestors are. While Java also provides reflection, it does so much more verbosely than Ruby.

Sample Code:


puts [1, 2, 3, 4, 5].length
Output: 5

puts "Hey".class 
Output: String

puts "John".class.superclass  # print the  superclass of  a String
Output: Object

puts String.ancestors #print the hierarchy
Output: String


Java Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

Key Features

The most luring feature is that one can access the metadata of classes and methods, getting the annotations and analyzing them dynamically. Other Advantages are as listed below:


An application may make use of external, user-defined classes by creating instances of extensible objects using their fully-qualified names.

A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.

Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discover-able set APIs defined on a class, to insure a high level of code coverage in a test suite.

The entry point for all reflection operations is java.lang.Class. With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors. To get to these classes, it is necessary to invoke appropriate methods on Class. There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class.


If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass(). Of course, this only works for reference types which all inherit from Object. Some examples follow.

Class c = "foo".getClass();

Returns the Class for String.

The .class Syntax: If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b;
Class c = b.getClass();   // compile-time error
Class c = boolean.class;  // correct

Note that the statement boolean.getClass() would produce a compile-time error because a boolean is a primitive type and cannot be de-referenced. The .class syntax returns the Class corresponding to the type boolean.

TYPE Field for Primitive Type Wrappers: The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type; however there is another way to acquire the Class. Each of the primitive types and void has a wrapper class in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.

Class c = Double.TYPE;

There is a class java.lang.Double which is used to wrap the primitive type double whenever an Object is required. The value of Double.TYPE is identical to that of double.class.

Methods that Return Classes: There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.


Returns the super class for the given class.

Class c = javax.swing.JButton.class.getSuperclass();

The super class of javax.swing.JButton is javax.swing.AbstractButton.


Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

Class[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and Character.UnicodeBlock.


Returns all of the classes interfaces, and enums that are explicitly declared in this class.

Class[] c = Character.class.getDeclaredClasses();

Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class Character.CharacterCache.


Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will have an enclosing class.

import java.lang.reflect.Field;

	Field f = System.class.getField("out");
	Class c = f.getDeclaringClass();

The field out is declared in System.

	public class MyClass {
    	static Object o = new Object() {
        public void m() {} 
   	static Class<c> = o.getClass().getEnclosingClass();

The declaring class of the anonymous class defined by the object "o" is null.


Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Reflection requires a run-time permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code, breaks abstractions and therefore may change behavior with upgrades of the platform [8]


Key Features

It enables you to do simple things like: Check the type of an object at runtime (simple calls to typeof() for example) Inspect the Attributes of an object at runtime to change the behavior of a method (the various serialization methods in .NET) To much more complicated tasks like: Loading an assembly at runtime, finding a specific class, determining if it matches a given Interface, and invoking certain members dynamically.


C# programmers are familiar with polymorphism based on interface inheritance. Reflection provides an alternative where we can invoke methods having same signature, from different classes not having a common interface.

If we need to write code that depends on class details known only at run time, then reflection comes as an easy way to proceed.

It is possible to write code for factory design pattern by loading classes using reflection instead of writing fixed code depending on specific static types with if-else statements inside the factory method.


To write a C# .Net program which uses reflection, the program should use the namespace System.Reflection. To get type of the object, the typeof operator can be used. There is one more method GetType() which also can be used for retrieving the type information of a class. The Operator "typeof" allows us to get class name of our object and GetType() method is used to get data about object's type. Suppose we have following class:

    public class TestDataType
        public TestDataType()
           counter = 1;

        public TestDataType(int c)
           counter = c;

        private int counter;

        public int Inc()
           return counter++;
        public int Dec()
           return counter--;


At first we should get type of object that was created. The following C# .Net code snippet shows how to do it [9]

	TestDataType testObject = new TestDataType(15);
	Type objectType = testObject.GetType();

Now objectType has all the required information about class TestDataType. We can check if our class is abstract or if it is a class. The System.Type contains a few properties to retrieve the type of the class: IsAbstract, IsClass. These functions return a Boolean value if the object is abstract or of class type. Also there are some methods that return information about constructors and methods that belong to the current type (class). It can be done in a way as it is done in next example:

	Type objectType = testObject.GetType();

	ConstructorInfo [] info = objectType.GetConstructors();
	MethodInfo [] methods = objectType.GetMethods();

	// get all the constructors
	foreach( ConstructorInfo cf in info )

	// get all the methods
	foreach( MethodInfo mf in methods )

Now, the above program returns a list of methods and constructors of TestDataType class.


Use of reflection exposes much of the implementation details such as the methods, fields, accessibility and other metadata of the class used.

The code that is reflective is slow than the direct code that performs the same functionality. As reflection performance also depends on the kind of operations that are done in the code like creating objects, accessing members, making method calls, etc.


Example in Smalltalk

w := Workspace new.
w openLabel:'My Workspace'
w inspect

Here we can inspect all the methods available to the instance 'w'.


Example in PHP
$reflector = new ReflectionClass("SimpleXMLElement"); 
echo $reflector;

Output of this example is the complete class map of the class SimpleXMLElement.

Comparison of Reflection in different languages

Java Ruby C# PHP C++
Supports Reflection Supports Reflection Supports Reflection Supports Reflection Poor support for Reflection [10]
Not Powerful and flexible as Ruby Reflection Provides powerful and flexible Reflection mechanism Not Powerful and flexible as Ruby Powerful and flexible Provides RTTI support which provides only a very restricted subset of reflection
Uses Reflection Ability to introspect as it is a dynamic language Uses Reflection Ability to type introspect as it is a dynamic language C++ supports type introspection via the typeid and dynamic_cast keywords
Variable's type determines its class and methods. Ruby supports liberated objects(cannot tell exactly what an object can do until you look under its hood) Variable's type determines its class and methods. Uses Reflection class It is possible to get object run-time type only if object class contains virtual functions(using RTTI)
Java Reflection API (is a bit higher level than the C# Reflection API) [11] Ruby has a rich set of Reflection APIs Has Reflection APIs Has Reflection APIs Has no Reflection APIs

Applications of Reflection

Advantages and disadvantages of reflection




This article makes an attempt to explain the concept of Reflection in Object Oriented Programming. The article mentions the different approaches to reflection in Ruby and other languages.It mentions the usage of Reflections and the advantages and disadvantages of using Reflection. A follow up to this article would be to study the concept of Metaprogramming.


  1. Brian Cantwell, Smith, "Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science", Massachusetts Institute of Technology, PhD Thesis, 1982
  2. Brian C. Smith, "Reflection and semantics in a procedural language", Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Mass., January 1982
  3. Metacircular Interpreter and Lisp
  4. Youssef Hassoun, Roger Johnson,Steve Counsell, "Reusability, Open Implementation and Java’s Dynamic Proxies",School of Computer Science and Information Systems
  5. Philip K. McKinley, Seyed Masoud Sadjadi, Eric P.Kasten, Betty H.C.Cheng, "Composing Adaptive Software", Michigan State University, July 2004.
  6. Load Time Structural Reflection
  7. JavaDoc for Reflection
  8. Disadvantages of Java Reflection API
  9. C# Reflection
  10. Tharaka Devadithya, Kenneth Chiu, Wei Lu, "Reflection for High Performance Problem Solving Environments", Computer Science Department, Indiana University, 2007
  11. Difference between Java and C# Reflection APIs
  12. Analysis of Programming Languages

Additional Reading

Personal tools