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.
- Finding out about class members.
- Using class members.
- Reading annotations.
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.
- Invoke methods.
- Invoke constructor.
- Changing the value of fields.
Invoke methods
- The program here invokes two methods first one is
public void m()
and the second one ispublic String m3(String str, int i)
c.getMethod("m3", String.class, Integer.TYPE)
In this example with the last two arguments, we are passing arguments types. The method can have the same name but different arguments(overloading) so just a name is not enough for methods with arguments.method3.invoke(obj1, "apple", 5);
The second argument here is actually varargs to pass the method arguments. And if there is no argument we can passnull
.
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"
getFields()
is different thangetDeclaredFields()
. It returns only accessible public fields. If we usegetDeclaredFields()
and try to set values for not accessible fields, we will have a runtime exception.
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!
Please take my Java Course for video lectures.This article is part of the series of articles to learn Java programming language from Tech Lead Academy:Introduction to programming
OS, File, and File System
Working with terminal
Welcome to Java Programming Language
Variables and Primitives in Java
Convert String to numeric data type
Input from the terminal in Java
Methods with Java
Java Math Operators and special operators
Conditional branching in Java
Switch statement in Java
Ternary operator in Java
Enum in Java
String class and its methods in Java
Loops in Java
Access modifiers in Java
Static keyword in Java
The final keyword in Java
Class and Object in Java
Object-Oriented Programming in Java
OOP: Encapsulation in Java
OOP: Inheritance in Java
OOP: Abstraction in Java
OOP: Polymorphism in Java
The method Overriding vs Overloading in Java
Array in Java
Data Structures with Java
Collection framework in Java
ArrayList in Java
Set in Java
Map in Java
Date and Time in Java
Exception in Java
How to work with files in Java
Design Patterns
Generics in Java
Multithreading in java
Annotations in Java
Reflection in Java
Reflection & Annotations - The Powerful Combination
Run terminal commands from Java
Lambda in Java
Unit Testing in Java
Big O Notation for coding interviews
Top Java coding interview questions for SDET