The Reflection API
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.
reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
1. Extensibility Features:An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
2. Class Browsers and Visual Development Environments
private
fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Class myObjectClass = MyObject.class;
Method[] method = myObjectClass.getMethods();
//Here the method takes a string parameter if there is no param, put null.
Method method = aClass.getMethod("method_name", String.class);
Object returnValue = method.invoke(null, "parameter-value1");
In above example the null parameter is the object you want to invoke the method on. If the method is static you supply null. If the method is not static, then while invoking you need to supply a valid MyObject instance instead of null.
Reflection also allows you to access private member/methods of a class:
public class A{
private String str= null;
public A(String str) {
this.str= str;
}
}
A obj= new A("Some value");
Field privateStringField = A.class.getDeclaredField("privateString");
//Turn off access check for this field
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(obj);
System.out.println("fieldValue = " + fieldValue);
- For inspection of classes (also know as introspection) you don't need to import the reflection package (
java.lang.reflect
). Class metadata can be accessed through java.lang.Class
.
Reflection is a very powerful API but it may slow down the application if used in excess, as it resolves all the types at runtime.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.