1. 程式人生 > >java通過反射獲取物件的變數和變數值

java通過反射獲取物件的變數和變數值

在java中如果類的成員變數設定為私有的,一般情況下是不允許直接訪問這個變數的,但是有了反射之後,就可以直接獲取該變數的名稱和變數值

1. 訪問成員變數

(1)先定義一個使用者實體類

public class User {

    private int id;
    private String name;
    private Date birth;

    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public
int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

(2)通過反射獲取該類

        /**動態載入類**/
        Class clazz = Class.forName("org.entity.User"
); /**獲取類宣告的變數**/ Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { /**列印變數名**/ System.out.println(field.getName()); }

2. 訪問成員變數值

(1)第一種方法,直接訪問

    public static void print() throws Exception{
        SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd"); User user = new User(); user.setId(1); user.setName("張三"); user.setBirth(sdf.parse("2017-08-16")); Class clazz = user.getClass(); Field[] fs = clazz.getDeclaredFields(); for (Field field : fs) { /** 如果成員變數是private的,則需要設定accessible為true 如果成員變數是public的,則不需要設定 **/ field.setAccessible(true); System.out.println(field.get(user)); } }

(2)第二種方法 呼叫變數的get方法

public static void print() throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        User user = new User();
        user.setId(1);
        user.setName("張三");
        user.setBirth(sdf.parse("2017-08-16"));
        Class clazz = user.getClass();
        Field[] fs = clazz.getDeclaredFields();
        for (Field field : fs) {
            /** 先獲取變數名 **/
            String fieldName = field.getName();
            /**拼接get方法,如getId  **/
            String getMethod = "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1,fieldName.length());
            /**
            呼叫clazz的getMethod方法獲取類的指定get方法
            通過invoke執行獲取變數值
            **/
            System.out.println(clazz.getMethod(getMethod).invoke(user));
        }
    }