Java Reflection is a process of examining or modifying the run time behavior of a class at run time.
The java.lang.Class class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.
The java.lang and java.lang.reflect packages provide classes for java reflection.
Where it is used
The Reflection API is mainly used in:
- IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
- Debugger
- Test Tools etc.
How to get the object of Class class?
There are 3 ways to get the instance of Class class. They are as follows:
- forName() method of Class class
- getClass() method of Object class
- the .class syntax
1) forName() method of Class class
- is used to load the class dynamically.
- returns the instance of Class class.
- It should be used if you know the fully qualified name of class.This cannot be used for primitive types.
Let's see the simple example of forName() method.
Output:Simple
2) getClass() method of Object class
It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.
Output:Simple
3) 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.It can be used for primitive data type also.
Output:boolean Test
No comments:
Post a Comment