CSC/ECE 517 Fall 2011/ch4 4f ss
Reflection
Reflection allows program entities to discover things about themselves through introspection.
In other words,Reflection is the ability of a program to determine information about an object at runtime.
The information may include the following :
- The type of the object
- Inheritance structure
- Methods it contains.
- Number of parameters of the methods,types of parameters, return types.
- Names and types of the attributes of the object.
Reflection is supported by many Object-oriented programminglanguages in various forms. Powerful and flexible reflection mechanisms are exhibited by Smalltalk, [1], and Python . Java also supports reflection. But reflection in java is verbose and is not as flexible and dynamic as these languages. C++ allows a program to determine the type of an object at run-time. Thus it does support reflection but in a limited form only. Eiffel also has support for a limited form of reflection which includes the ability to determine the features contained in an object.
Reflection in Ruby
Examples of reflection in ruby :
puts "hello".class #returns the class of object "hello"
Output:
String
puts "hello".class.superclass #returns the superclass of the String class
Output:
Object
puts string.ancestors #returns the ancestors of the string class
String
Comparable Object Basic Object Kernel
Obtaining Reference to a
Reflection in Java
Reflection in Java is much more verbose than in ruby.It is an advanced feature of the Java environment. Reflection is achieved using the Reflection API.The verbosity of reflection in java may be associated with the usage of the library for reflection.
Big industrial-strength protocols like SOAP and JavaBeans wouldn't be possible if it weren't for Reflection. Every time you drag-and-drop an object in your favorite IDE into a form, Reflection is orchestrating the action behind the scenes. Actually, most sophisticated Java applications rely on Reflection in one way or another.
Reflection is an advanced feature of the Java environment. It gives runtime information about objects, classes, and interfaces. Some of the questions that can be answered using reflection in java:
* Which class does an object belong to? * What is the description of a given class name? * What are the fields in a given class? * What is the type of a field? * What are the methods in a class? * What are the parameters of a method? * What are the constructors of a given class? * Constructing an object using a given constructor * Invoking an object's method using such-and-such parameters * Assigning a value to an object's field * Dynamically creating and manipulating arrays
Java Reflection Classes
All Reflection classes (With the exception of the class Class that resides in the default Java package) are contained in the package java.lang.reflect.
Following are some of the classes used to various represent members of a class.: Classes-'Class' class Fields-'Field' class methods-'Method' class constructors-'Constructor' class arrays-'Array' class.
Illustration of Reflection in Java through Examples
Class
Each class or interface in Java is described by a Class object.It contains methods to obtain details about the class like name, parent class, constructors, fields, methods, interfaces implemented etc.
To obtain the class that an object belongs to, invoke the method Class getClass()(returns 'Class') of the 'Object' class (superclass of all the Java classes hierarchy)
String myStr = "HelloWorld"; Class theClass = myStr.getClass(); // 'theClass' now contains 'String'
The property ".class"(available for every java class) returns a Class object for the class.
String myStr = "HelloWorld"; if (myStr.getClass()==String.class) System.out.println("The object is a String"); // prints "The object is a String"
The wrapper classes (Integer, Boolean, Double,...) contain a ".TYPE" property that returns the Class object representing the primitive type.
Class myClass = Integer.TYPE; //
Field
The Field class describes the different attributes of a Java class field. Information such as a field name, its type, and its accessibility can be obtained from a field object. It also contains methods to set and get the field's value for a given object
Example
import java.lang.reflect.*; public class MyfieldClass { int i = 100; String s = "Hello World"; public static void main(String args[]) { try { Class cls = Class.forName("MyfieldClass"); Field flist[]= cls.getDeclaredFields(); for (int i = 0; i < flist.length; i++) { Field f = flist[i]; System.out.println("name = " + f.getName()); System.out.println("decl class = " + f.getDeclaringClass()); System.out.println("type = " + f.getType()); } } catch (Throwable e) { System.err.println(e); } } }
The output of the program is:
name = i decl class = MyfieldClass type = double name = s decl class = MyfieldClass type = class java.lang.String
Method
The Method class is used to obtain information(the method name, its type, its accessibility, and its parameter types) about class methods.We can even invoke the method on a particular object and pass a set of parameters to it.
import java.lang.reflect.*; public class myMethodClass { private int myMethod(int y, int x) { return x+y; } public static void main(String args[]) { try { Class cls = Class.forName("myMethodClass"); Method mlist[] = cls.getDeclaredMethods(); for (int i = 0; i < mlist.length;i++) { Method m = mlist[i]; System.out.println("name= " + m.getName()); System.out.println("decl class = " +m.getDeclaringClass()); Class pt[] = m.getParameterTypes(); for (int j = 0; j < pt.length; j++) System.out.println("param #" + j + " " + pt[j]); System.out.println("return type = " + m.getReturnType()); } } catch (Throwable e) { System.err.println(e); } } }
The output of the program is:
name = myMethod decl class = class myMethodClass param #0 int param #1 int return type = int name = main decl class = class myMethodClass param #0 class [Ljava.lang.String; return type = void
Constructor
The Constructor class can be used to obtain information(parameter types, number of parameters, and accessibility) about class constructors.We can also invoke the constructor to create new object instances
import java.lang.reflect.*; public class Myconstructor { public Myconstructor() { } public static void main(String args[]) { try { Class c = Class.forName("Myconstructor"); Constructor clist[]= c.getDeclaredConstructors(); for (int i = 0; i < clist.length; i++) { Constructor ct = clist[i]; System.out.println("name= " + ct.getName()); System.out.println("Declaring Class Name = " + ct.getDeclaringClass()); Class pTypes[] = ct.getParameterTypes(); for (int j = 0; j < pTypes.length; j++) System.out.println("param #" + j + " " + pTypes[j]); } } catch (Throwable e) { System.err.println(e); } } }
output:
Name=MyConstructor Declaring Class name=MyConstructor
Applications of Reflection in Java:Many sophisticated Java applications rely on reflection
- Reflection is used extensively in protocols like SOAP
- Whenever we drag-and-drop an object in an IDE to use it in a form, Reflection is used behind the scenes.
- Java Beans
- It is used in Debuggers and Test Tools which require examining the private members <ref>http://download.oracle.com/javase/tutorial/reflect/</ref>.
- It is used class browser which needs to be able to enumerate the members of classes.
- It is also employed in Visual development environments. The type information available in reflection is used to help the developer in writing correct code.
Benefits
- Reflection helps in keeping software robust
- It helps in making the applications more flexible,extensible and pluggable.
- It helps in making the source code more readable.
- It can simplify source code and design.
- Expensive conditional code can be reduced/removed.
See more: http://download.oracle.com/javase/tutorial/reflect/