Title: Reflection
1Reflection
2What is Reflection?
- Reflection is a way that an object can find out
about itself, or about other objects and classes. - What is the name of this class?
- What attributes does it have?
- What methods does it have?
- What are the parameters and return type of
methods?
3Getting a Class by Name
- Create a "Class" object.
- You must use the fully qualified name (String).
Class cl null try cl Class.forName(
"java.lang.Math" ) catch(ClassNotFoundException
e) return null // couldn't find this
class return cl // return reference to this
class
4Getting a Class's Methods
- getDeclaredMethods( ) methods of this class only.
- getMethods( ) gets all methods, incl. inherited
ones.
// get the methods of Class referred to by
cl Method methods cl.getDeclaredMethods() fo
r( Method m methods ) // get the name of the
method out.println( m.getName() ) // get
parameters Class params m.getParameterTypes(
) // get return type Class ret
m.getReturnType( )
5Invoking a Class's Methods
- Simple example invoke Math.sqrt( 0.5 )
// get a class object for Math class Class cl
Class.forName("java.lang.Math") if ( cl null
) return // class object for the Double
class Class doubleCl Class.forName("java.lang.Dou
ble") // get the "sqrt" method with one "double"
param Method m cl.getMethod("sqrt", doubleCl)
try Double argsDbl new Double 0.5
Double ans (Double) m.invoke(null,
argsDbl) return ans.doubleValue() catch(
Exception e ) ... handle the exception ...
6Invoking a Class's Methods
- Create an array of parameter values.
- Use the "invoke" method.
/ invoke method m with arguments args / static
double eval(Method m, double args) throws
ParseException // TODO verify correct number
of parameters Double argsDbl new
Doubleargs.length for(int k0 kltargs.length
k) argsDblk argsk try Double d
(Double) m.invoke(null, argsDbl) return
d.doubleValue() catch( Exception e ) ...
handle the exception ...
7Exceptions from invoke
- Hey, can we use "invoke" to invoke private
methods? - This would bypass the access privilege system!
Method invoke throws IllegalAccessException,
IllegalArgumentException, InvocationTargetExce
ption
8Applications of Reflection
- JavaBeans uses reflection to discover properties
of beans. - JUnit uses reflection to discover methods to test.
9Reflection in Calculator
- Use reflection to add all the functions in
java.lang.Math to your calculator. - Only required add functions that accept one
double argument. - If your calculator can only handle functions with
0, 2, ... parameters, then add those functions,
too. - Use the invoke method of Method class to call a
method when the user inputs it. - More later...