Core Java Tutorials


Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package


Exception Handling


Immutable Class

File Handling




Concurrent Package


Collection Internal



Reflection In Java


Class Loader

Java Inner classes

Garbage Collector


References In Java

Heap Dump & Thread Dump

Reflection In Java


  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. ... println("method = " + method. getName());

  Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

  Lots of modern frameworks like Spring, Hibernate, Struts 2.x , JSF 2.x use reflection extensively for this very reason... In other words using reflection we can fetch all the information's of a class even though we do not know class name at the compile time.

  Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

  java.lang.Class- As per java doc , Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types boolean, byte, char, short, int, long, float, and double, and the keyword void are also represented as Class objects.

The following example uses a Class object to print the class name of an object:

 public final
    class Class implements,
                              java.lang.reflect.AnnotatedElement {
  void printClassName(Object obj) {
     System.out.println("The class of " + obj +
                             " is " + obj.getClass().getName());

java.lang.Class is the entry point for all the reflection operations because all class informations are store inside the method area in Class type of objects. JVM instantiates an immutable instance of java.lang.Class for every classes loaded inside the JVM that and java.lang.Class provides methods to examine the runtime properties of the object and create new objects, invoke its method and get/set object fields etc.

  Printing name of class using reflection

  Creating an Object Using a Constructor Object

 Instantiating a class with private constructor

 Annotation Processing with reflection

 Real Example of Reflection in JSP/Servlet Container