Monday, August 25, 2014

What is Reflection API? Advantages of Reflection API and Disadvantages of Reflection API

The Reflection API allows Java code to examine the classes and objects at run time.
The new Reflection classes allows you to call another class methods dynamically a the run time

EXAMPLE

Say you have an object of unknown type in java, you would like to call a method, dosomething on it if it exists

Static typing languages isn't really designed to support this, unless the object conforms to a known interface. But with reflection your code can look at the object and find if it has a method called dosomething and then call if it want to

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Learn_reflection {


public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {


Learn_reflection t = new Learn_reflection();
Method met[] = t.getClass().getMethods();

for(int i = 0; i<met.length; i++){
if(met[i].getName().equals("Test1")){
met[i].invoke(t);
}
}
}

public void Test1() {
System.out.println("Test1");
}

public void Test2() {
System.out.println("Test2");
}

}


Advantages of Reflection API
1) Helps to look at the methods and objects at run time

DisAdvantages of Reflection API
1) Performance overload, since everything is dynamically resolved, JVM may not be able to perform certain optimizations
2)Security Restrictions : Refecion requires runtime permission to the code, which might not always be allowed

No comments:

Post a Comment