Reflection in Java
Reflection in Java
Reflection is an API which is used to determine or modify the behavior of methods, classes, interfaces at runtime.
- All required classes for reflection are provided in java.lang.reflect package.
- Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
- Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.
Reflection can be used to get information about –
- Class The getClass() method is used to get the name of the class to which an object belongs.
- Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.
- Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.
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.
class Simple{} class Test{ public static void main(String args[]){ Class c=Class.forName("Simple"); System.out.println(c.getName()); } }
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.
class Simple{} class Test{ void printName(Object obj){ Class c=obj.getClass(); System.out.println(c.getName()); } public static void main(String args[]){ Simple s=new Simple(); Test t=new Test(); t.printName(s); } }
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.
class Test{ public static void main(String args[]){ Class c = boolean.class; System.out.println(c.getName()); Class c2 = Test.class; System.out.println(c2.getName()); } }
boolean Test
post a comment