I was asked a question: "What do you know about reflection in Java?" I wasn’t really confident while answering that question, so let’s get a bit wiser and polish my rusty knowledge.

What Is Reflection?

Reflection is a very powerful API that allows to scrutinize and/or modify classes and their properties, interfaces, methods, anotations, etc. at runtime.

Tools for utilizing the reflection are located in package java.lang.reflect

The entry gate to reflection is method Object.getClass() which returns an instance of Class object (Class documentation). Through this object, you can access for example the fields, methods or annotations of the original object. You can read and modify their access modifiers, access private members and basically do whatever you wish. Welcome to the godmode.

What Is It Good For?

Dependency injection containers use reflection heavily to look up injectable dependencies and to create their instances. It is useful for dynamically spawning components, for example if you write a framework which can load jar plugins at runtime. However, that is quite an advanced Java mojo for writing really big applications.

There are some drawbacks of using reflection in the code. It is quite demanding if you utilize reflection for example over big number of objects at once (iterating through a List), hence the performance of the application might be severely decreased.