Java Reflection API
Java reflection api provides the facility to inspect or examine and modifying the run-time behavior of a class or application at run-time. we can get the classes, interfaces, fields, instantiate new objects, invoke methods and get/set field values without knowing the names of the classes, methods. Its provide some methods that can be used to get the metadata about the class, data about data, examine, modifying the run-time behavior of a class.
Example:
class Test
{
public static void main(String args[])throws ClassNotFoundException
{
Class c = Class.forName("Test");
System.out.println(c.getName());
}
}
(1) public String getName()
This method returns the name of the entity(class, interface, array class, primitive types and void) represented by this Class's object in the form of String.
(2) pubic static Class forName(String classname)throws ClassNotFoundException
This method loads the class and returns the reference of Class class.
(3) public boolean isInterface()
This method checks if it is interface or not.
(4) public boolean isArray()
This method checks if it is array or not.
(5) public boolean isPrimitive()
This method checks if it is primitive or not.
(6) public Class getSuperclass()
This method returns the super class reference.
(7) public Object newInstance()throws InstantiationException, IllegalAccessException
Creates a new instance.
(8) public ClassLoader getClassLoader()
Returns the class loader for the class.
(9) public int getModifiers()
This method returns the java modifiers for this class or interface, encoded in an integer.
(10) public Method[] getDeclaredMethods()throws SecurityException
Returns the total number of methods of this class.
Example:
class Test
{
public static void main(String args[])throws ClassNotFoundException
{
Class c = Class.forName("Test");
System.out.println(c.getName());
}
}
Methods Available in Reflection Api
(1) public String getName()
This method returns the name of the entity(class, interface, array class, primitive types and void) represented by this Class's object in the form of String.
(2) pubic static Class forName(String classname)throws ClassNotFoundException
This method loads the class and returns the reference of Class class.
(3) public boolean isInterface()
This method checks if it is interface or not.
(4) public boolean isArray()
This method checks if it is array or not.
(5) public boolean isPrimitive()
This method checks if it is primitive or not.
(6) public Class getSuperclass()
This method returns the super class reference.
(7) public Object newInstance()throws InstantiationException, IllegalAccessException
Creates a new instance.
(8) public ClassLoader getClassLoader()
Returns the class loader for the class.
(9) public int getModifiers()
This method returns the java modifiers for this class or interface, encoded in an integer.
(10) public Method[] getDeclaredMethods()throws SecurityException
Returns the total number of methods of this class.
Comments
Post a Comment