[Java」PropertyUtils クラスのsetPropertyメソットでJavaBeanのプロパティを設定するサンプル

jarファイル
commons-beanutils-1.9.4
commmon-collection-3.2.2(※3.x系必須)
構文
PropertyUtils.setProperty(beanオブジェクト名, プロパティ名, 値);
1.UserDataクラスの定義

package com.arkgame.java.study;

public class UserData {

      private String username;
      private String pwd;

      public UserData() {

      }

      public String getUsername() {
            return username;
      }

      public void setUsername(String username) {
            this.username = username;
      }

      public String getPwd() {
            return pwd;
      }

      public void setPwd(String pwd) {
            this.pwd = pwd;
      }

}

2.setProperty()でJavaBeanのプロパティを設定する

package com.arkgame.java.study;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;

public class UserDataList {

      private static List<UserData> userList;

      public static void main(String[] args) {
            intUserList();
      }

      private static void intUserList() {
            userList = new ArrayList<UserData>();

            for (int i = 0; i < 3; i++) {
                  UserData userData = new UserData();
                  try {
                        // メンバー変数username(プロパティ)
                        PropertyUtils.setProperty(userData, "username", "admin_" + i);
                        // メンバー変数pwd(プロパティ)
                        PropertyUtils.setProperty(userData, "pwd", "pwd25_" + i);
                        userList.add(userData);
                  }

                  catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                        e.printStackTrace();
                  }
            }
            System.out.println("実行結果");
            for (UserData ud : userList) {
                  System.out.println("username: " + ud.getUsername() + " password: " + ud.getPwd());
            }

      }
}

実行結果
username: admin_0 password: pwd25_0
username: admin_1 password: pwd25_1
username: admin_2 password: pwd25_2

Java

Posted by arkgame