Java — Reflection API

Ben Parker
2 min readJan 7, 2021

I’ve known Java for around 4 years now. I’ve been steadily improving my skills but there are some features of the language that I have hardly ever touched. Partly due to laziness, but mostly due to having a day job that doesn’t require me to know them in any great detail. The Reflection API is one of these features.

I have read a little bit about it and want to summarise what I have learned.

Overview

The reflection API is a feature of Java which was introduced in Java 8. It allows you to modify and invoke classes in code, without knowing the specific details of that class at compile time.

This API will allow you to:

  • Find information on a class such as its parent, any interfaces, all method names or constructor names as well as parameters and types
  • Instantiate a class using its constructor
  • Invoke methods you think might exist
  • Modify method names
  • Alter method access modifiers
  • Access and change private variables

Some of these features circumvent Java compile time security checks such as type safety and access modifiers. It is for this reason that the Reflection API is so powerful. It is also for this reason, that so many people have a negative view towards using Reflection in your code design.

Since Java is built around the premise of type safety, the Reflection API is something that should only be used if absolutely necessary. When designing your system, I think it can be avoided in most cases.

Use Cases

There are some cases, where Reflection is a suitable design choice such as:

ORM ( Object Relational Mapping )
Maintaining a relationship between fields in an object and fields in a database

Remote Method Calling
Treat a string received over the network as a method name. If a server sends a message which contained the string “<ClassName>.toString()”: you could parse this message and use reflection to invoke the “toString()” method of that class.

IDE
Eclipse gives you a prompt when you create a sub-class of an abstract parent class: it tells you which methods need to be implemented. This is done via the Reflection API.

Calling methods in third party libraries
You don’t always have direct access to the methods themselves, so you may need to use reflection to access to class at Runtime and invoke a method you think exists.

Annotations
Any framework which uses Annotations ( JAX-RS, Jersey, Spring ) is likely using the reflection API. More written about Annotations here .

Code
I have written a utilities class to help using reflection. It is stored at the following github page

https://github.com/BDBenParker/JavaUtils

--

--