Reflection Api
Reflection Api
Presentation by
Abrar Faiyaz(124405)
Reflection API
What is it & why use it?
One useful real-world use of reflection is when writing a framework that has
to interoperate with user-defined classes, where the framework author
doesn't know what the members (or even the classes) will be. Reflection
allows them to deal with any class without knowing it in advance. For
instance, I don't think it would be possible to write a complex aspect-oriented
library without reflection.
For every loaded class, the Java Runtime Environment (JRE) maintains an
associated Class object
Can use the Class object to discover information about a loaded class
name
modifiers (public, abstract, final)
super classes
implemented interfaces
fields
methods
constructors
Can instantiate classes and invoke their methods via Class object
How it works
Accessing the Class object for a loaded class:
Example Code
static void showMethods(Object o) {
Class c = o.getClass();
Method[] theMethods = c.getMethods();
for ( int i = 0; i < theMethods.length; i++) {
String methodString = theMethods[i].getName();
System.out.println("Name: " + methodString);
String returnString =
theMethods[i].getReturnType().getName();
System.out.println(" Return Type: " + returnString);
Class[] parameterTypes = theMethods[i].getParameterTypes();
System.out.print(" Parameter Types:");
for (int k = 0; k < parameterTypes.length; k ++) {
String parameterString = parameterTypes[k].getName();
System.out.print(" " + parameterString);
}
System.out.println();
}
}
Additional features
Can instantiate objects and invoke methods via information obtained from the
reflection API.
Introspection
Dynamic Instantiation
c = c.getSuperclass();
System.out.println("base class of note = " +c.getName());
c = c.getSuperclass(); System.out.println("base of base class
of note = " + c.getName());
Here is the output produced:
base class of note = Note
base of base class of note = java.lang.Object
Note note;
note = new HornNote();
Class c = note.getClass();
System.out.println("class of note = " + .getName());
note = new ViolinNote();
c = note.getClass();
System.out.println("now class of note = " +c.getName());
The output produced would be:
class of note = HornNote
now class of note = ViolinNote
Introspection
Illustrating with Examples
class UniversalInstrument {
public void play(String noteType) {
try {
Class c = Class.forName(noteType);
// find & load a class
Note note = (Note) c.newInstance();
note.play();
} catch (Exception e) { // handle e here }
}
}
We don't know what the user will enter, so we don't know what type of notes to
make.
}
The body of the class to be loaded:
public class MyClass implements AnInterface {
//... body of class ... implement interface methods
}
Thank you