How to use the Field class to get and set class fields in Java

How to use the Field class to get and set class fields in Java

This is how to use the Field class to get and set the fields of a class in Java.

Suppose we have a DTO class called SampleDto.

The fields are as follows.

String name;
BigDecimal age;

You can get the type of the field with dto.getType().

If dto.getType() is BigDecimal, you can get the superclass of BigDecimal, Number, with dto.getType().getSuperclass().

Each of the DTO properties can be obtained as follows

for (Field field : dto.getClass.getDeclaredFields()) {
}

Below is the usage of the Field class.

package jp.confrage;

import java.lang.reflect.Field;
import java.math.BigDecimal;

public class Test1{
  public static void main(String[] args) {
    SampleDto dto = new SampleDto();
    dto.setName("Yamada");
    dto.setAge(BigDecimal.TEN);

    for (Field field : dto.getClass().getDeclaredFields()) {
      field.setAccessible(true);
      System.out.println(field.getName());
      try {
        System.out.println(field.get(dto));
      } catch (IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
      }
      System.out.println(field.getType());
    }
  }
}

The results are as follows

name
Yamada
class java.lang.String
age
10
class java.math.BigDecimal

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL