Example & Tutorial understanding programming in easy ways.

What is Reflection API in Java?

Reflection in java provides ability to inspect and modify the runtime behavior of applications. Reflection is one of the advance topic of core java. Using reflection we can inspect a class,interface, enums, get their structure, methods and fields information at runtime even though class is not accessible at compile time.

The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier.

Reflection in Java

Reflection is a very powerful concept and it’s of little use in normal programming but it’s the backbone for most of the Java, J2EE frameworks. Some of the frameworks that use reflection are:
1 JUnit – uses reflection to parse @Test annotation to get the test methods and then invoke it.
2 Spring – dependency injection, read more at Spring Dependency Injection
3 Tomcat web container to forward the request to correct module by parsing their web.xml files and request URI.
4 Eclipse auto completion of method names
5 Struts
6 Hibernate

Need of reflection

1 Examine an object's class at runtime
2 Construct an object for a class at runtime
3 Examine a class's field and method at runtime
4 Invoke any method of an object at runtime
5 Change accessibility flag of Constructor, Method and Field


Example : Get class name from object

package myreflection;

import java.lang.reflect.Method;

public class ReflectionHelloWorld {

public static void main(String[] args){

Test t= new Test();

System.out.println(t.getClass().getName());

}

}

class Test {

public void print() {

System.out.println("abc");

}

}

Read More →