Reflection in Java

Today we will talk about reflection in Java. The main credit and source used for this article is an official oracle article.

Reflection is when code can reflect a source code or we can say when code can read itself. By using reflection we can find out about members of the specific class during the code execution. We also can call a method of a specific class without knowing its name before running and so on.

  1. Finding out about class members.

Finding out about class members

Let’s say we have this class and we want to find out more about it via reflection.

The output of this will be

Now let’s see how we can see all fields of the class.

and the output

So you got an idea. Similarly, you can find out about declared constructors.

Using class members

We can do a lot more with reflections. We will still work on our MyClass class.

  1. Invoke methods.

Invoke methods

  • The program here invokes two methods first one is public void m() and the second one is public String m3(String str, int i)

Invoke constructor

That’s how we can create a new object of the class by using reflection. Calling a constructor with arguments has similar logic with a methods call.

Changing the value of fields

  • The above code assigns each accessible(by access modifier) String property of the object to "java is cool"

Reading annotations

Let’s have NotNull.java annotation

plus RestClient.java annotation

and RequestMethod.java enum file

public enum RequestMethod {
GET, POST, PUT, DELETE
}

Let’s change MyClass.java file

We are using our annotations created earlier.

And finally our Main.java with reflection

output:

We can read annotations by using reflection in java. The combination of annotations and reflection is used in modern frameworks such as Spring, JUnit, and many others.

Summary

The reflection is the ability of the program to inspect the source code. And as I mentioned earlier is a great tool to create frameworks. If we just think about any framework, the main idea would be to give specific roles for classes and assign specific features. Then the user will write the custom logic. For example, in the Spring we have controllers, services, repositories. We tag them by using annotations(or XML configs) and they automatically will receive extra features to behave based on their role in the framework. So the reflection is used here to scan and find out classes and their role. I will open this topic in more detail in another article.

Thank you and have a wonderful day!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store