Im going through Reflection in java and its main purpose is to inspect classes at RunTime.
May I know what does inspecting classes mean ?
Im going through Reflection in java and its main purpose is to inspect classes at RunTime.
May I know what does inspecting classes mean ?
Inspecting means finding out what fields and methods class has. What are signatures of those methods. What annotations are present on the methods, fields and class itself.
This is needed for some type of infrastructural code. For example a library that takes an instance of an arbitrary class (that is the class the the author of the library know nothing about beforehand) and saves it into database. It needs to know what fields the class has to save them to appropriate columns in the database.
You can get a Class
object for any Java object or class, like this:
Class cls = String.class
or:
Class cls = "abcd".getClass()
In each case here, cls
gives you a reference to the String
type's Class
object.
You can then call methods on that Class
object to learn things about the original object or class, like about its methods, fields and annotations. Take a look at the documentation of Class.
There is a series of classes representing the parts of a class, like Method
, Constructor
and Field
. You can look those up in the Java docs as well.