CSC/ECE 517 Fall 2012/ch1b 1w40 ar: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
==Introduction==
==Introduction==
By looking at the mirror, we can see our image and we can act on what we see like straightening the tie. In [http://en.wikipedia.org/wiki/Computer_programming Software programming], Reflection is a feature of some [http://en.wikipedia.org/wiki/Programming_language programming languages] and [http://en.wikipedia.org/wiki/Scripting_language scripting languages] that allows them to change their own structure at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) run-time]. For example in a high level [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented languages ]the ability to inspect its class, interfaces and methods at run time without knowing their names at [http://en.wikipedia.org/wiki/Compile_time 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.
By looking at the mirror, we can see our image and we can act on what we see like straightening the tie. In [http://en.wikipedia.org/wiki/Computer_programming Software programming], Reflection is a feature of some [http://en.wikipedia.org/wiki/Programming_language programming languages] and [http://en.wikipedia.org/wiki/Scripting_language scripting languages] that allows them to change their own structure at [http://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase) run-time]. For example in high level [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented languages ] the ability to inspect its class, interfaces and methods at run time without knowing their names at [http://en.wikipedia.org/wiki/Compile_time 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.


==Background==
==Background==

Revision as of 22:26, 30 September 2012

Introduction

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.

Background

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<ref>Brian Cantwell Brian Cantwell Smith, Procedural Reflection in Programming Languages, Department of Electrical Engineering and Computer Science, Massachusetts Institute of Technology, PhD Thesis, 1982</ref><ref>Brian C. Smith. Reflection and semantics in a procedural language. Technical Report MIT-LCS-TR-272, Massachusetts Institute of Technology, Cambridge, Mass., January 1982</ref> introduced the notion of computational reflection in programming languages, and the notion of the meta-circular interpreter as a component of 3-Lisp<ref>Metacircular Interpreter and Lisp</ref>.

Types of reflection

There are two basic types of reflection. They are:

  • Behavioral Reflection:
  • Structural Reflection:

Behavioral Reflection<ref>Metaprogramming and Behavioral Reflection </ref>

This type of reflection changes the behavior of the execution of the program based on observation and modification.

Structural Reflection<ref>Load Time Structural Reflection</ref>

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.

Implementation

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 essense 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:

  • Ability to convert a string that denotes a class or a method into its corresponding reference or invocation.
  • Ability to use and create symbolic links to methods and classes.

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

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:

3.14159.methods

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
	Enumerable    
	Comparable
	Object
	Kernel

Java

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:

  • Extensibility Features

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

  • Class Browsers and Visual Development Environments

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 and Test Tools

Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable 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.

Object.getClass()

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 dereferenced. 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.

Class.getSuperclass()

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.

Class.getClasses()

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.

Class.getDeclaredClasses()

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.

Class.getDeclaringClass()
java.lang.reflect.Field.getDeclaringClass()
java.lang.reflect.Method.getDeclaringClass()
java.lang.reflect.Constructor.getDeclaringClass()

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 o is null.

Disadvantages:

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.

  • Performance Overhead

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.

  • Security Restrictions

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.

  • Exposure of Internals

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.

C#

Key Features:

  • Signature Based Polymorphism

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.

  • Inspecting and Manipulating Classes

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.

  • Creating Adaptable and Flexible Solutions

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.

Example:

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(). This also can be used for retrieving the type information of a class. The Operator typeof allow us to get class name of our object

and GetType() method uses 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.

	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 was done in next example:

	Type objectType = testObject.GetType();

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

	// get all the constructors
	Console.WriteLine("Constructors:");
	foreach( ConstructorInfo cf in info )
	{
	   Console.WriteLine(cf);
	}

	Console.WriteLine();
	// get all the methods
	Console.WriteLine("Methods:");
	foreach( MethodInfo mf in methods )
	{
	   Console.WriteLine(mf);
	}

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

Disadvantages:

  • Exposes Implementation Details

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

  • Performance

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

Smalltalk

Example in Smalltalk

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

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

PHP

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
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 C# Reflection API. Ruby has a rich set of Reflection APIs C# Reflection API is a bit lower level than Java Reflection API. Has Reflection APIs Has no Reflection APIs


Applications of Reflection

  • Reflection has become invaluable to programmers who need to connect code with data. For example in a GUI environment a button might need to invoke different methods in different classes. Reflection can be used here to call the method on any given class.
  • Programmers who deal with a multitude of classes at the same time can use reflection to create a “serializer” that for a given class uses reflection to go through all the instance variables and processes them accordingly.
  • Reflection is used in large test frameworks where reflection helps in identifying the test methods for different scenarios.
  • Reflection provides the ability to morph the code based on dynamic situations. This provides a sense of artificial intelligence to the program as whole.
  • Reflection can be used to debug and verify code as it provides access to the insides of a program.
  • Reflection is very useful when the software is upgraded regularly. It provides an easy method to check for available methods and classes. This prevents the errors caused by the absence of methods and classes when they are deprecated.

Advantages and disadvantages of reflection<ref>Analysis of Programming Languages</ref>

Advantages

  • Extensibility: Reflection provides the capability of using external and user defined classes by instantiation of extensibility objects using their fully qualified names.
  • Class browsers in IDEs: The ability to examine the members of classes makes implementation of visual aids , auto-completion and documentation easy in development tools for programmers.
  • Debugging: Reflection allows the user to observe the private members in classes. This capability can be used to debug classes and their interactions.
  • Test Harness : Reflection can be used to call a set of testing APIs defined on a class for maximum coverage of testing.
  • Correctness : Reflection improves the robustness and the correctness of a program especially in dynamically typed languages as runtime checks can be added to check the availability of the methods or classes.

Disadvantages

  • Reflection introduces lot of performance overhead when compared to non-reflective code. Hence it should be used judiciously.
  • Since it provides access to the internals of a class or an encapsulated object security becomes a major issue.
  • Since it is run-time binding we lose the security of compile time checks and verification.

Conclusion

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.

References

<references />

Additional Reading