Introduction
In this article, we discuss reflection in Java. Reflection is the process of determining or modifying the behavior of a class at runtime. Java provides a java.lang.Class class that contains many methods, that help in finding metadata and to change the runtime behavior of a class.
What are the uses of Reflection?
It is mainly used in:
- Integrated Development Environments (IDEs), for example, Eclipse, MyEclipse, NetBeans etcetera.
- Test Tolls
- Debugger etcetera.
This class generally used to performs two tasks
- they have a method, that is used to find and changes the runtime behavior of a class.
- they provide methods, that get the metadata of a class at runtime.
Some Drawbacks of reflection
- Performance overhead
- Security Restrictions
- Exposure of Internals
Some commonly used public methods of the Class class
- String getName()
- static Class forName(String className) throws ClassNotFoundException
- Object newInstnce() throws InstantiationException, IllegealAccessException
- boolean isInterface()
- boolean isArray()
- boolean isPrimitive()
- Class getSuperclass()
- Field[] getDeclaredFields() throws SecurityException
- Method[] getDeclaredMethods() throws SecurityException
- Constructor[] getDeclaredConstrutors() throws SecurityException
- Method getDeclaredMethod(String name, Class[] parameterTypes) throws NoSuchMethodException, SecurityException
How to determine the Object of the class at runtime
- By using forName() method.
- By using getClass() method
- By using .class syntax
1. Use of the forName() method
Example
- class Reflection {}
- class Check {
- public static void main(String args[]) throws ClassNotFoundException {
- Class cls = Class.forName("Reflection");
- System.out.println(cls.getName());
- }
- }
Output
2. By using the getClass() method
Example
- class Reflection {}
- class Check {
- void printName(Object ob) {
- Class cls = ob.getClass();
- System.out.println(cls.getName());
- }
- public static void main(String args[]) {
- Reflection ref = new Reflection();
- Test tst = new Test();
- tst.printName(ref);
- }
- }
Output
3. By using the .class syntax
Example
- class Check {
- public static void main(String args[]) {
- Class cls1 = Check.class;
- System.out.println(cls1.getName());
- Class cls = boolean.class;
- System.out.println(cls.getName());
- }
- }
Output