Reflection:
To obtain meta level information about the program structure itself at runtime.
To change the program interpretation or meaning at the runtime
What is meta level information?
Meta-information is information on the information held within a data set (wikipedia).
Examples:
Meta information for a journal article (the data): the abstract, the conclusion, the authors, the publisher, …
Database schema
MetaData of ResultSet
In “normal” programs you don’t need reflection
You do need reflection if you are working with programs that process programs
Examples:
A class browser
A debugger
An IDE, such as BlueJ, Netbeans or eclipse A program to check student programs
In Java, reflection enables to discover and make use of information about the loaded classes:
Modifiers
Fields
Methods
Constructors
Etc.
java.lang.reflect provides a number of classes and methods for checking the above information:
java.lang.reflect.Constructor;
java.lang.reflect.Field;
java.lang.reflect.Method;
java.lang.reflect.Modifier;
The Class class
The starting point for using reflection is always a java.lang.Class instance.
If you have an object obj, you can get its class object with
Class cls = obj.getClass();
If you know the name of a class (say, Calculator) at compile time,you can get its class object with
Class cls = Calculator.class;
If you know the name of a class at run time (in a String variable str), you can get its class object with
Class cls = class.forName(str);
Task: Write code to: Check how many methods does the Rectangle class has Print out the return type of each method Print out the parameter types of each method Invoke the calculateArea method by using the instance created in the previous example (demo3).
public void checkMethod(Object obj){ Method mList[]=obj.getClass().getDeclaredMethods(); try { for(int i=0; i<mList.length;i++){ System.out.println("method name: "+mList[i].getName()+"" + " retrun type: "+mList[i].getReturnType()); Class[] cls=mList[i].getParameterTypes(); if(cls.length!=0){ for(Class c: cls) System.out.println(c.getName()); } else System.out.println("no argument"); mList[i].invoke(obj); } } catch (Exception ex) { Logger.getLogger(ReflectionDemo.class.getName()).log(Level.SEVERE, null, ex); } }
Task: Write code to: Check how many constructors does the Rectangle class has Print out the parameter types of each constructor Create a new rectangle instance where len=2.5 and wid=3.2, by using Constructor.newInstance().
Constructor[] cons=aCls.getConstructors(); Object obj1=null; for(Constructor c: cons){ System.out.println("constructor of "+c.getName()); Class[] paraTypes=c.getParameterTypes(); for(Class pt: paraTypes){ System.out.println(pt.getName()); } if(paraTypes.length==2) obj1= c.newInstance(2.5, 3); }
Task: Write code to: Print out the names and types of all declared fields of Circle Create an instance of Circle: cir Print out the values of all accessible double fields of cir. If the value of a double field is 0, set it to 1.
Field fList2[ ]=aCls.getDeclaredFields(); Object cir=aCls.newInstance(); for(int i=0; i<fList2.length;i++) { String fieldName=fList2[i].getName(); int fMod=fList2[i].getModifiers(); System.out.print(fieldName+": "); Class c=fList2[i].getType(); System.out.println(c.getName()+", “+Modifier.toString(fMod)); if(c.getName().equals("double") && fMod==Modifier.PUBLIC) { double fv=fList2[i].getDouble(cir); System.out.println(fieldName+" = "+fv); if(fv==0) fList2[i].setDouble(cir, 1); }