Reflection API feature in Java – Overview
Tags: java, api
Published: 2022-09-16 10:27:40

## **I. Introduction.**

This is the first post from series of articles with main subject – Java reflection.
In this article, I am going to explain the basic concepts of reflection – what is it, when it is being used, why and show examples for its usage.

## **II. What is Reflection in terms of Java?**

Reflection is powerful feature implemented in Java and it allows to the executing Java program to examine or to modify internal properties **at runtime**.

The packages, which are required in order to use the features, which Reflections API provides are in reflect, you can import them using following:

`import java.lang.reflect.*;`

Reflection gives an information about the class to which one object belongs to. In addition to that – the methods of the class that can be executed with the usage of the object.

## **III. Example 1: Print methods of a given class.**
Let see the feature in practice.

The demo contains following files:

    * Cat.java
    * CatRflDemo.java

in class Cat, we have following:

**Cat.java**
```
public String name;
private int years;
private boolean isHungry;

public void setName(String name) {
    this.name = name;
}

public String getName() {
    return this.name;`
}

public void sayMEOW() {
    System.out.println("MEOW!");
}
```

In order to get and to print the methods, which are in Cat class, we use snipper similar to this bellow:

```
Method[] catMethods = Cat.class.getMethods();
for(Method mthd : catMethods) {
    System.out.println(mthd.getName() + "()");`
} 
```

This will print all of the methods of class CAT.

After executing this, the following result will be printed in console:

getName()
setName()
wait()
wait()
wait()
equals()
toString()
hashCode()
getClass()
notify()
notifyAll()

As you may notice, there are methods, which are extended and aren’t written by us like toString(). 

## **IV. Example 2 – Set value to a field.**
Another great feature, which is part of Reflection API is the option to set value to a field.

I will use Cat class for this example. In the cat class, I added some fields. Here is it:

```
public String name;
	
private int years;
private boolean isHungry;
	
public void setName(String name) {
	this.name = name;
}
	
public String getName() {
	return this.name;
}
	
private void sayMEOW() {
       System.out.println("MEOW!");
}
	
public boolean isTheCatHungry() {
       return this.isHungry;
}
```
As you see there is new method called isTheCatHungry. In the main class put this:
```
Cat catObj = new Cat();

System.out.println("Is the cat hungry?" + catObj.isTheCatHungry());

Field flds[] = catObj.getClass().getDeclaredFields();

for(Field fld : flds) {
     if(fld.getName().equals("isHungry")) {
          fld.setAccessible(true);

  try {
        fld.set(catObj, true);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

   }
}

System.out.println("Is the cat hungry?" + catObj.isTheCatHungry());
```

Here we create object of Cat called catObj and print the default value of the variable isHungry. After that, we need an array to store all of the declared fields, so this is what the purpose of flds array is. Followed by iteration through the array.

The line: if(fld.getName().equals(“isHungry”)) {}
checks the field, which is going to be accessed, which in this case is called “isHungry” and after this it is being set to accessible, so we could control it and on the next step it is being modified with the following method fld.set(catObj, true);

After running this snippet, the output will be something like this:
`Is the cat hungry?false`
`Is the cat hungry?true`


## **V. Conclusion.**
Java Reflection API provides great variety of features. In this article some of them are being shown. Each feature provided by Reflection API has its advantages, but when using it, the dev should warn. Just as Oracle wrote it – if operation could be made without using reflection, it is preferable to avoid it. However, Java’s reflection API is really usefull and could help dev to learn more in depth how the stuff works inside VM.

In the next article from this series I will cover more details, explore more features of Reflection API, and give more in depth examples.

Thank you for reading this article! If you have any questions – feel free to comment.