Monday, May 13, 2013

Java Reflection API: Introduction

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.  It enable applications to perform operations which would otherwise be impossible. An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
Thus Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

The Drawbacks of reflection are:

  • Performance overhead
  • Security restrictions
  • Exposure of internals
Creating a Class Object when you don't know the class name at runtime:
String className = ??? //get fully qualified classname at runtime
Class mClass = Class.forName(className);
The Class.forName() method may throw a ClassNotFoundException if the class cannot be found on the at runtime.

You can access the modifiers ("public", "private", "static" etc.) of a class via the Class object. 

int modi = mClass.getModifiers();
Now using java.lang.reflect.Modifier , you can check the modifier info, for example:
Modifier.isAbstract(modi);

You can access the constructors of a class like this: 
Constructor[] constructors = mClass.getConstructors();
You can access the methods of a class like this:
Method[] methods = mClass.getMethods();
You can access the fields of a class like this:
 Field[] fields = mClass.getFields();
Next post in the series is Java Reflection API: Constructing Objects

No comments:

Post a Comment