Ref:http://www.studytonight.com/java/reflection-api
Reflection API
Reflection means ability of a software to analyze itself. In Java, Reflection APIs provides facility to analyze and change runtime behavior of a class, at runtime
For Example, using reflection at the runtime can determine what method or modifiers a class supports
What is the reflect package?
Java.lang.reflect Package encapsulates serveral important interface and classes. These classes and interface define methods which is used for reflection
Class description
----------------------------------------------------------------------------------------------------------
Array allow you to dynamically created and manipulate arrays
Constructor gives info abt Constructor of a class
field provides info abt field
Method Procide Info Abt method
Modifier provide info abt class and member access Modifier
Proxy supports dynamic proxy classes
Java.lang.Class is another important class used in Reflection API
Uses of Reflection
1. Developing IDE
2. Debugging and Test Tools
3. Loading drivers and providing dynamic info
Disadvantages of Reflection
1. Low performance
2. Security risk
3. Violation of OOPs concept
cut**************************
Reflection Class
Java.lang.Class
Class is a final class Injava.lang package which extends Object class. Instance of this class
Represents classes and interfaces in a running Java application. It is used to analyze and change dynamic behavior of a class at runtime
Some Important Methods of Java.lang.Class Class
This class defines several methods using which we can get info on methods, constructors, modifiers and members of a CLA SS at runtime
Forname ()
1. This method takes fully qualified name of the classes or nterfaces as its argument and return instance
of the class associated with it.
2. Static class<?> forname (String className)
Class Student{}class test{public static void Main (String args[]) { class.forname("Student"); System.out.println (c.getname ()); }}
Output:student
GetConstructors () and Getdeclaredconstructors ()
1. GetConstructors () returns array of constructors object that represent all the public constructors of the invoking OBJEC T. This method is only returns public constructor. Getdeclaredconstructors () would return all constructors
Constructor GetConstructors (); Constructor getdeclaredconstructors ();
Example using GetConstructors () and Getdeclaredconstructors () method
Class C = class.forname ("Student"); c.getconstructors (); for (int i=0; i< ct.length; i++) {System.out.println (ct[i]);} c.getdeclaredconstructors (); for (int i=0;i< cdt.length;i++) {System.out.println (cdt[i]);}
Output
Public Student () public Student () Student (java.lang.String)
GetMethods () and Getdeclaredmethods () GetFields () and Getdeclaredfields () Example using GetFields () and Getdeclaredfields () method
Java Reflection API | Java.lang.Class