Reflection API : A Brief Introduction:-
"Reflection API is a powerful technique (that provides the facility)
to find-out its environment as well as to inspect the class itself.
Reflection API was included in Java 1.1."
The classes of
Reflection API are the part of the package java.lang.reflect and the methods of
Reflection API are
the parts of the package java.lang.class. It allows the user to get the complete information about
interfaces, classes, constructors, fields and
various methods being used. It also provides an easy
way to create a Java Application that was not possible before Java 1.1. You can create
methods like event handlers, hash code etc and also find-out the objects and classes.
With the help of Reflection API you can get the information about any class of the java.lang package. There are some useful methods like getName() and getInterfaces(), which allows us to retrieve the name of the class and the interfaces of the package respectively.
1. Getting the implemented Interfaces:-
In this section you will learn how to retrieve an Interface (that
included in the program) by using the getInterfaces() method. Here is an
example that provides the usage of the getInterfaces() method in more
detail.
Create an object of class Finterface and assign it with
java.util.Integer.class.. Now retrieve Interfaces (included in the program)
and store their references in an array of class Class by using the getInterfaces() method.
Finterface.java:
import java.lang.reflect.*;
|
interface java.util.Collection
Retrieving the class name through Reflection API:-
A more generic way, how to retrieve the name of the class (that is used in the program) that reflects the package name by using the getName() method. Here is an example that provides the proper way to use the getName() method.
Here we create an object of class Fclass and assign the reference of the class java.util.Integer.class to it. Now retrieve the class name (that is included in the program) by using the getName() method.
Here is the code of the Example :
Fclass.java-
import java.lang.reflect.*;
|
Here is the output of the Example :
java.lang.Integer
Finding out the super class name of the class:-
Create a class "Fsupercls". Populate it with the Checkbox objects. Now retrieve the Superclass name by using the getSuperclass() method.
Here is the code of the Example :
Fsupercls.java:
import java.lang.reflect.*; |
Here is the output of the Example :
class java.awt.Component
Getting the method name used in the Application:-
Define a class named "Fmethod" and then create an object of this class and get the reference of java.util.Integer.class into it. Now retrieve the method name by using the getMethods() method.
Here is the code of the Example :
Fmethod.java:
| import java.lang.reflect.*;
|
hashCode
No comments:
Post a Comment