Reflection in Java

Ibnu Arseno
Code Storm
Published in
5 min readFeb 8, 2022

In this article, we will discuss reflection in java, what is a reflection in java and what are features that we can use in the projects we make.

Photo by Maximilian Weisbecker on Unsplash

Java reflection is a Java feature that allows Java programs to learn or modify themselves. When the application is on-runtime, the application can modify itself or even see its structure of itself.

For example, we can see the structure of a java class starting from all fields, methods, constructors, and others when the application is running. Java reflection is widely used by frameworks because it is very powerful.

the features of java reflection are contained in 2 packages, namely in java.lang and java.lang.reflect. There are lots of classes in Java Reflection, and we will discuss them in this article.

Inspecting Java Classes

java.lang.Class<T> is a reflection representation for Java Class, Interface, and Enum. Sometimes when creating a Java Class, Interface, or Enum we add fields and methods. With the capability of java.lang.Class, we can read all member data (such as fields or methods) contained in a Java Class, Interface, or Enum when the application is running. we can read the details in the documentation.

to create a Class<T> we can do several ways:

  1. use the .class keyword after the name of the Java Class, Interface, or Enum. example: Person.class, Repository.class, or Gender.class.
  2. using String using the static method Class.forClass(“com.example.Person”) class name must be followed by its package name.
  3. or we can retrieve the Class<T> of the object, by using the getClass() method.

we will create a Person class as an example:

public class Person {  private String firstName;  private String lastName;  public Person() {}  public Person(String firstName, String lastName) {    this.firstName = firstName;    this.lastName = lastName;  }// getter setter// to String}

to create a Java Reflection Class by:

Class<Person> personClass = Person.class;

The result is a Java reflection Class with a generic type Person. or by using String like:

Class<?> personClass = Class.forName("com.example.Person")

when using the generic type String use <?>. Or by retrieving the Class<?> of the object using the getClass() method:

Person person = new Person()Class<? extends Person> personClass = person.getClass();

Class<T> has a lot of methods. such as to get fields, methods, constructors, annotations, superclasses, interfaces, and others. We can read all the details of the method in the Javadoc.

Inspecting Fields

The field is a representation of the Java Field contained in the Java Class. to get a public Field, we can use the getFields() method. or if you want to get all fields with all visibility, we can use the getDeclaredField() method. or you can also get a Field based on its Field name using the getField(field name) or getDeclaredField(field name) methods.

The field is the same as for Class<T>, it has a lot of methods that can be used to view the details of the field, such as data type, field name, annotation, and others. For more details, see the documentation. sample program to get Field:

Class<Person> personClass = Person.class;Field[] fields = personClass.getDeclaredFields();for (Field field : fields) {  System.out.println(field.getName() + " : " + field.getType().getName());}

Retrieve or change a Field Object

Fields can retrieve and modify fields from existing objects. For example, we have created a Field, then we have an Object person1, then we want to take the value of the Field or change it, we can use the setXxx() or getXxx() methods on the field.

sample program to get Field value:

Class<Person> personClass = Person.class;Field firstName = personClass.getDeclaredField("firstName");firstName.setAccessible(true);Person person1 = new Person("Evans", "Frank");String result = (String) firstName.get(person1);System.out.println(result);

sample code to change Field value:

Class<Person> personClass = Person.class;Field firstName = personClass.getDeclaredField("firstName");firstName.setAccessible(true);Person person1 = new Person("Evans", "Frank");firstName.set(person1, "Max"); // person1.setFirstName("Max");System.out.println(person1.getFirstName());

in the example code above we use the previous Person class, for example, we take a Field with value firstName. so that the Field can be accessed the setAccessible(true) method is set to true.

Inspecting Methods

besides Field, we can also get Methods available in Class<T>. the way to get it is the same as Field, we can use the getMethods(), getDeclaredMethod(), getMethode(name), and getDeclaredMethod(name) methods.

in Method, many methods can be used to get information such as return value, name annotation, parameters, and others. For more details, see the documentation. Sample code to get Parameters:

Class<Person> personClass = Person.class;
Method[] methods = personClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
System.out.println("Parameter Name : " + parameter.getName());
}
}

Inspecting Constructors

Constructor<T> is a representation of Java Constructor in Java Class. Constructor<T> is similar to Method, in that it has parameters. to create a Constructor we get it via Class<T>.

Constructor<T> is a generic data type, following the generic data type of Class<T>. For more details, see the documentation. Sample code to get the Constructor:

Class<Person> personClass = Person.class;Constructor<?>[] constructors = personClass.getDeclaredConstructors();for (Constructor<?> constructor : constructors) {System.out.println(constructor.getName());System.out.println(Arrays.toString(constructor.getParameterTypes()));}

Super Class

In many cases, especially when using a Java class library or built-in class, we may not know in advance the superclass of the object we are using, this subsection will show you how to obtain this information.

by using Java Reflection, we can also find out the Super Class of a Java Class. there is a getSuperclass() method in Class<T> to get the Super Class. when creating a class if you don’t add a super class, the super class will automatically be the java.lang.Object class. For more details, see the documentation. Sample code to get Super Class:

Class<Person> personClass = Person.class;System.out.println(personClass);Class<? super Person> objectClass = personClass.getSuperclass();System.out.println(objectClass);

Implemented Interfaces

using Java Reflection we can also get a list of interfaces implemented by a particular class.

for the sample code, add a Nameable interface then implement it on Class Person:

public interface Nameable {  String getFirstName();  String getLastName();}

sample code to get interface:

Class<Person> personClass = Person.class;System.out.println(Arrays.toString(personClass.getInterfaces()));

It is therefore worth noting that only those interfaces that a class explicitly declares as implemented with the implements keyword appear in the returned array.

Package Information

Using Java reflection, we can also get information about packages from any class or object. We can get Package from Class<T> by using getPackage() method. For more details, see the documentation. Sample code to retrieve the package name:

Class<Person> personClass = Person.class;Package aPackage = personClass.getPackage();System.out.println(aPackage.getName());

Class Modifiers

A modifier is a representation of Java Modifier, such as private, protected, public, abstract, and others. We can determine the modifiers used in a class by calling the getModifiers method which returns an Integer. Each modifier is a flag bit that is either set or cleared. For more details, see the documentation. Sample code to get Modifier:

Class<Person> personClass = Person.class;System.out.println(Modifier.isPublic(personClass.getModifiers()));System.out.println(Modifier.isFinal(personClass.getModifiers()));System.out.println(Modifier.isStatic(personClass.getModifiers()));

Conclusion

In this article, we covered the Java Reflection API and saw how to use it.

--

--