Wednesday, July 1, 2020

Java Reflection

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
 
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.


       DeclaredMethod - gives all types of method of a class
       getMethods - - it does not return protected and private methods but reurtn super class method as well .
       
we can fetch field value using get method , we can set value , get value of fields. To set private field values we have to first set isAccessible true  then only we. can set the value.
we can fetch values for constructor or Methods

       void is also a class
       class<?>c = obj.getClass() = to get class
       Class.forName(className)  = to get class

       field.toString = to get field Info
       field.toGenericType to get Genric Type as well


       c.getSuperClass = to check if it contains super class
       Modifier.isPublic - to check access specifield of method, counstroctor or field
       Array.newInstance - to create a new intance of type array
       cls.newInstance - to create a new instance of any Type except array

No comments:

Post a Comment