1

Im going through Reflection in java and its main purpose is to inspect classes at RunTime.

May I know what does inspecting classes mean ?

kaya3
  • 47,440
  • 4
  • 68
  • 97
MeghanaO
  • 37
  • 3
  • 6

2 Answers2

1

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.

  • 3
    "*This is needed for some type of infrastructural code*" Reflection is not really *needed*. Other languages get by just fine without it. It's just the way a lot of Java frameworks tend to function. You could do much the the same things with compile-time code generation. Take, for example, Micronaut vs Spring – Michael Sep 22 '20 at 16:27
1

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.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44