0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

リフレクションを使用してDTOのString項目に空文字をセットする

Last updated at Posted at 2025-03-06

リフレクション(Reflection)とは?

リフレクション とは、プログラムが実行時にクラスやオブジェクトの構造(フィールド、メソッドなど)を動的に調べたり変更したりできる仕組み です。

通常、Java のオブジェクトは コンパイル時に型が決まっている ので、メソッドやフィールドに直接アクセスすることができます。
しかし、リフレクションを使うと、クラスの情報を実行時に動的に取得・操作 できます。

UserDTO.java
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

class UserDTO {
    private int id;
    private String name;
    private String email;
    private boolean isActive;
    private Integer age;

    // コンストラクタ
    public UserDTO(int id, String name, String email, boolean isActive, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.isActive = isActive;
        this.age = age;
    }

    // ゲッター
    public int getId() { return id; }
    public String getName() { return name; }
    public String getEmail() { return email; }
    public boolean isActive() { return isActive; }
    public Integer getAge() { return age; }

    // セッター(リフレクション用)
    public void setName(String name) { this.name = name; }
    public void setEmail(String email) { this.email = email; }
}
main.java
public class DtoUtil {
    public static void clearStringFields(Object dto) {
        Field[] fields = dto.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getType().equals(String.class)) { // String 型のみ変更
                field.setAccessible(true);
                try {
                    field.set(dto, ""); // String フィールドを空文字にする
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        // DTOリスト作成
        List<UserDTO> dtoList = new ArrayList<>();
        dtoList.add(new UserDTO(1, "Alice", "alice@example.com", true, 25));
        dtoList.add(new UserDTO(2, "Bob", "bob@example.com", false, 30));

        // すべての DTO の String フィールドを空文字にする
        dtoList.forEach(DtoUtil::clearStringFields);

        // 確認(String は空文字に、他の値は変更なし)
        for (UserDTO dto : dtoList) {
            System.out.println("ID: " + dto.getId());       // 変更なし
            System.out.println("Name: " + dto.getName());   // 空文字 ("")
            System.out.println("Email: " + dto.getEmail()); // 空文字 ("")
            System.out.println("Active: " + dto.isActive()); // 変更なし
            System.out.println("Age: " + dto.getAge());     // 変更なし
            System.out.println("----------------------");
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?