21-Reflection

Download Report

Transcript 21-Reflection

Reflection
What 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?
Getting a Class by Name

Create a "Class" object.

You must use the fully qualified name (String).
Class clazz = null;
try {
clazz = Class.forName( "java.lang.Math" );
} catch(ClassNotFoundException e) {
// couldn't find it in the classpath
// or Java standard locations
}
Getting a Class's Methods

getDeclaredMethods( ) methods of this class only.

getMethods( ) gets all methods, incl. inherited ones.
Method [] methods = cl.getDeclaredMethods();
for(Method m : methods) {
out.println( m.getName() );
// get parameters
Class [] params = m.getParameterTypes();
// get return type
Class ret = m.getReturnType( );
}
Invoking a Class's Methods
Create an array of parameter values.
 Use the "invoke" method.

static double eval(Method m, double [] args)
throws ParseException {
//TODO: verify that args matches requires
// parameters for this method
Double [] argsDbl = new Double[args.length];
for(int k=0; k<args.length; k++)
argsDbl[k] = args[k];
try {
Double d = (Double) m.invoke(null, argsDbl);
return d.doubleValue();
} catch( Exception e ) {
... handle the exception ...
}
Exceptions from invoke

Wow, can we use "invoke" to invoke private methods?

This would bypass the access privilege system!
Method invoke
throws
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
Applications of Reflection

JavaBeans uses reflection to discover properties of
beans.

JUnit uses reflection to discover methods to test.

Hibernate uses reflection to create objects and inject
values.
Reflection in Calculator

Use reflection to add all the functions in java.lang.Math
to your calculator.

Only include the functions that accept one double
parameter.

If your calculator can handle functions with 0, 2, ...
parameters, then add those functions, too.

Use the invoke method of the Method class to call a
method when the user inputs it.

More later...