Java
: Reflection
Reflection
is the process of examining or modifying the runtime behavior of a
class at runtime.
Java.lang.Class
class
*
provide methods to get the metadata of a class at runtime
*
provide methods to examine and change the runtime behavior of a
class.
Get
the object of Class class
-
forName() method of Class class
-
getClass() method of Object class
-
the .class syntax
forName()
*
forName() is used to load class dynamically.
*
returns the instance of Class class
*
should be use full qualify name of the class
getClass()
*
Returns the instance of Class class.
*
It should be use if the object is available.
The
.class syntax
If
a type is available but there is no instance then it is possible to
obtain a Class by appending “.class” to the name of the type.
This
can be used to Primitive Data Type also.
package
O1Concepts.Reflection;
/**
*
@author
sanjeeva
*
Reflection
- is the
process of examining or modifying the runtime behavior of a class at
runtime
*
forName()
*
getClass()
*
.class
*/
public
class
Reflection {
/**
* @param
args
*/
public
static
void
main(String[] args) {
Reflection
reflection = new
Reflection();
reflection.execute();
}
private
void
execute(){
try
{
//forName()
..
Class
cls = Class.forName("O1Concepts.Reflection.Simple");
System.out.println("Name[
forName() ] --> " +
cls.getName());
//getClass()
...
Simple
simple = new
Simple();
Class
objClass = simple.getClass();
System.out.println("Name[
getClass() ] --> " +
objClass.getName());
Class<Integer>
type = Integer.class;
System.out.println("Name[
.class :1 ] --> " +
type.getName());
Class<Reflection>
ref = Reflection.class;
System.out.println("Name[
.class :2 ] --> " +
ref.getName());
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Output
-
Name[
forName() ] --> O1Concepts.Reflection.Simple
Name[
getClass() ] --> O1Concepts.Reflection.Simple
Name[
.class :1 ] --> java.lang.Integer
Name[
.class :2 ] --> O1Concepts.Reflection.Reflection