Anda di halaman 1dari 13

Reflection

Reflection API facilitate dynamic management of classes. Using this API following task can be performed. 1. Classes can be loaded dynamically 2. Information of classes can be obtain dynamically 3. Classes can be instanceated indirectly 4. Method can be invoked indirectly 5. Data member can be manipulated indirectly etc.

java.lang.reflect package provide classes and interfaces of reflection API. Before using reflection API we must understand class representation of java.
For each class which is loaded during the execution of application an object of type java.lang.Class is created by the JRE. Thats at the time of execution information of each class is stored in an object of type class. Processes of storing information of a class into a class object is called ClassLoading.

To managed classes in object form the class named java.lang.Class is provided by Sun Microsystem. For each class which is used in an application an object of type Class is created. The process of creating a class object of a Class is called Class Loading.

Following diagram describe the process of Class Loading

In order to interact to a class object reference of the object need to be obtain. Reference to a class object can be obtain in the following three base: 1. If name of the class is known then reference of class object is obtain using the implicit data member name Class. Syntax: ClassName.class example for classes A & B Reference of these class Objects can be obtained as:A----> Class c1 = A.class; B----> Class c2 = B.class; 2. If name of the class is not known but an object of the class available then reference of the class object for the class can be obtain using the getClass() method of the object. Syntax: public class getClass();

example: following code is written in Throwable class to describe exceptions. public String toString() { return getClass.getName()+":"+detailMessage; } 3. If name of the class is made available only at the time of execution then its class object can be obtain by getting the class loading using forName() method name of type class. public static Class forName(String className)throws ClassNotFoundException; e.s:- following block of code will load the class Name of which is received as command line argument. try { Class c = Class.forname(args[0]); ---} catch(Exception ex) { --}

--------------------Commonly used methods java.lang.Class

1. getName():- is used find out the name of a class. public String getName(); 2. getFields():- is used find out the details of declared as well as inherited data members of a class. public Field[] getFields(); this method return array of type java.lang.reflect.field each elements of the array represent the information of data members. 3. getDeclaredFields():- is used to find out the information of all the data members which are declared in the class. public Field[] getDeclaredField(); 4. getMethods():- is used to find out the information of declared as well as inherited method of a class. public Method[] getMethods(); this method return array of type java.lang.reflect.Method each elements of the array represent the information of method of class.

5. getDeclaredMethods():- is used to find out details of only those methods which are declared in the class. public Method[] getDeclaredMethod(); 6. getConstructors():- is used to find out information of constructor of a class. public Constructor[] getConstructors(); this method return array of type java.lang.relfect.Constructor each constructor object describe the constructor of a class. 7. newInstance():- is used to created object of a class. public Object newInstance()throws Exception; etc Example
// Name of a class is received as command line argument, contents of the class are displayed on the console. import java.lang.reflect.*; public class Reflection { public static void main(String args[]) { try {

Class c = Class.forName(args[0]); Field f[]=c.getDeclaredFields(); for(int i=0;i<f.length;i++) System.out.println(f[i]); Constructor ctr[]=c.getDeclaredConstructors(); for(int i=0;i<ctr.length;i++) System.out.println(ctr[i]); Method m[]=c.getDeclaredMethods(); for(int i=0;i<m.length;i++) System.out.println(m[i]);

} catch(Exception ex) { System.out.println(ex); } } }

----------------Java.lang.reflect.Method class provides a method name invoke. To invoke a method indirectly. Syntax: Public Object invoke(Object o, Object[] args,)throws Exception; Note: 1. In case of static method, value of first parameter remain null.

2. In case a method does not receive parameters value of second parameters remain null.
//An execution engine is being defined which receives a class name as command line argument and executes the class. Assumption is each class contains a method named start() as entry point. import java.lang.reflect.*; public class Test { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Method m=c.getDeclaredMethod("start",null); m.invoke(null,null); } catch(Exception ex) { System.out.println(ex); } } } class A { public void show() { System.out.println("Welcome in Core java.."); } public static void start() { System.out.println("Start() of A invoked.."); }

} class B { public static void start() { System.out.println("Welcome in Class B."); } } class C { }

//execute non-static method


//An execution engine is being defined which recieves a class name as command line argument and executes the class. Assumption is that the class contains one or more non static methods all of which are to be invoked. import java.lang.reflect.*; public class Test { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Object target = c.newInstance(); Method []m=c.getDeclaredMethods(); for(int i=0;i< m.length;i++) m[i].invoke(target,null); } catch(Exception ex)

{ System.out.println(ex); } } } class A { A() { System.out.println("Constructor of class A"); } public void show() { System.out.println("Welcome in Core java.."); } public void start() { System.out.println("Start() of A invoked.."); } } class B { B() { System.out.println("Constructor of class B"); } public void Time() { System.out.println("Welcome in Class B."); } public void rinku() { System.out.println("Very dishonest friend..."); }

} class C { }

//Access Private Data from another class

//An execution engine is being defined which recieves a class name as command line argument and executes the class. Assumption is that the class contains one or more non static methods all of which are to be invoked. import java.lang.reflect.*; public class Test { public static void main(String args[]) { try { Class c = Class.forName(args[0]); Constructor ctr = c.getDeclaredConstructor(null); ctr.setAccessible(true); Object target = ctr.newInstance(); Method []m=c.getDeclaredMethods(); for(int i=0;i< m.length;i++) { m[i].setAccessible(true); m[i].invoke(target,null); } } catch(Exception ex)

{ System.out.println(ex); } } } class A { A() { System.out.println("Constructor of class A"); } public void show() { System.out.println("Welcome in Core java.."); } public void start() { System.out.println("Start() of A invoked.."); } } class B { private B() { System.out.println("Constructor of class B"); } private void Time() { System.out.println("Welcome in Class B."); } private void rinku() { System.out.println("Very dishonest friend..."); }

} class C { }

Anda mungkin juga menyukai