Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Standard view
Full view
of .
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1
Understanding and Using Reflection

Understanding and Using Reflection

Ratings: (0)|Views: 1,336 |Likes:
Published by sgganesh
see www.joyofprogramming.com
see www.joyofprogramming.com

More info:

Published by: sgganesh on Jun 02, 2009
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less





Understanding and Using Reflection
Reflection is a powerful language feature. Java supports ‘structural-reflection’, which is safe to use. With reflection, it is possible to do two basic types of operations on code: inspection and manipulation. Reflection enables using ‘signature based polymorphism’ as an alternative to ‘interface based polymorphismin Java.Reflection also facilitates creation of flexible and adaptablframeworks and patterns, which is not usually possible with direct code. Though there are many clear advantages in using reflection,like any other language feature, reflection can be misused. This article covers a few specific problems and solutions to illustrate uses and misuses of reflection.
 In programming, reflection is the ability to dynamically create, use or manipulateclasses and objects at runtime. For example, you can create an instance of a class,examine the class to find a specific method from that class and execute thatmethod with the arguments you specify, all this dynamically at runtime usingreflection.Reflection is not a new concept. Smalltalk – one of the early and important OOprogramming language – supported reflection in 1970s itself. Reflection is possibleonly when sophisticated runtime support is available in the languageimplementations. C++ follows static compilation model where the code is compiled tonative code and executed; the runtime support is limited. So reflection is notpossible in C++. However, Java and C# have sophisticated runtime mechanisms (JVMfor Java and CLR for .NET), so reflection can be supported in these languages.One of the misconceptions about reflection is that it is difficult to learn or use. Bylearning a few APIs and basic concepts, even beginners can write simple code usingreflection. However, like any other language feature, effective use of reflectiontakes effort and considerable experience.The reflection feature supported by languages like Java and C# is known as‘structural reflection’ where only inspection and execution of the code is allowed.There is another form of reflection more sophisticated than ‘structural reflection’,known as ‘behavioral reflection’, which allows us to modify or manipulate the code atruntime [1]. For strongly-typed, commercially widely used languages like Java,‘structural reflection’ suffices.Reflection is a powerful feature and it is very useful for creating dynamic oradaptable design and for writing development tools. Reflection is also often misusedby the programmers. In this article, after a short example for showing a how wewrite reflection code in Java, we’ll see the advantages, disadvantages, uses andmisuses of reflection with focus on disadvantages and misuses of reflection.
Reflection Example: Class Dissection
We’ll see small sample program to understand how we can use reflection in Java.Java’s java.lang.Class encapsulates the class that is the basic execution unit of theJava language. This class deals with Java class representation as a whole, and theclasses in the java.lang.reflect package deal with the parts of this class, such asmethods and fields.Let us consider an example that dissects a class using reflection (with the output ofthe program shown in comments):
class Reflect {public static Constructor [] constructors;public static Method [] methods;public static Field [] fields;public static Class thisClass; 
static {
try {thisClass = Class.forName("Reflect");// dissect and see this class itself!}catch(ClassNotFoundException cnfe) {System.out.println("class doesn't exist " + cnfe);System.exit(-1);}constructors = thisClass.getConstructors();methods = thisClass.getMethods();fields = thisClass.getFields();}public static void main(String []args) {System.out.println("This class is "+ thisClass);for(int i = 0; i < constructors.length; i++)System.out.println("Ctor "+ i + " " + constructors[i]);for(int i = 0; i < methods.length; i++)System.out.println("Method " + i + " " + methods[i]);for(int i = 0; i < fields.length; i++)System.out.println("Field " + i + " " + fields[i]);}} // output:// This class is class Reflect// Method 0 public static void//Reflect.main(java.lang.String[])// Method 1 public native int java.lang.Object.hashCode()// Method 2 public final native java.lang.Class
//java.lang.Object.getClass()// Method 3 public final void//java.lang.Object.wait(long,int) throws//java.lang.InterruptedException// Method 4 public final void java.lang.Object.wait()//throws java.lang.InterruptedException// Method 5 public final native void java.lang.Object.wait(long)// throws java.lang.InterruptedException// Method 6 public boolean//java.lang.Object.equals(java.lang.Object)// Method 7 public java.lang.String java.lang.Object.toString()// Method 8 public final native void java.lang.Object.notify()// Method 9 public final native void//java.lang.Object.notifyAll()// Field 0 public static java.lang.reflect.Constructor[]// Reflect.constructors// Field 1 public static java.lang.reflect.Method[]//Reflect.methods// Field 2 public static java.lang.reflect.Field[]//Reflect.fields// Field 3 public static java.lang.Class Reflect.thisClass 
This code is designed to peek into its own .class file and see what constructors,methods and fields are available inside. The whole code can be written within themain method itself, but this slightly contrived example has fields and a constructorfor illustration. Since all the classes inherit from Object the methods of that classare also shown in the output.
Advantages of Reflection1) Signature-Based Polymorphism
Java and C# programmers are familiar with polymorphism based on interfaceinheritance. Reflection provides an alternative where we can invoke methods havingsame signature, from different classes not have a common interface (which isrequired in interface based polymorphism). For example, we can implement dynamicobserver pattern or command pattern (dynamic design patterns) which invoke amethod based on same signature from classes not related to each other byinterface inheritance.
2) Inspecting and Manipulating Classes
Writing direct code is based on depending on specific class details (like interface,method or field names) known at compile-time. If we need to write code thatdepends on class details known only at runtime, then reflection comes handy.

Activity (3)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
Chinmaya Sahu liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->