「Java」getDeclaredFields() でクラスのメンバー変数を取得するサンプル

書式
public Field[] getDeclaredFields() throws SecurityException

サンプルコード

package com.arkgame.study;

import java.lang.reflect.Field;

public class MemberInfo {
      public static void main(String[] args) {

            Class<User> cft = User.class;
            Field[] ff = cft.getDeclaredFields();
            System.out.println("メンバー変数");
            for (Field f : ff) {
                  System.out.println(f);
            }
      }
}

class User {
      private String username;
      protected String address;
      public String school;

      public String getSchool() {
            return school;
      }

      public void setSchool(String school) {
            this.school = school;
      }

      public String getAddress() {
            return address;
      }

      public void setAddress(String address) {
            this.address = address;
      }

      public String getUsername() {
            return username;
      }

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

}

実行結果
メンバー変数
private java.lang.String com.arkgame.study.User.username
private java.lang.String com.arkgame.study.User.address
private java.lang.String com.arkgame.study.User.school

Java

Posted by arkgame