Java之BeanUtils測試代碼

這裏的代碼一定要按照JavaBean規範來寫

public class User{
    private int id ;
    private String name;
    private String password;

    public User() {
    }

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    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;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

import com.qfedu.a_statement.User;
import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

/**
 * Beanutils測試
 */
public class Demo1 {
    @Test
    public void tsetSetProperty() throws InvocationTargetException, IllegalAccessException {
        //自動類型轉換
        User user = new User();
        //給符合JavaBean規範的指定成員變量賦值
        BeanUtils.setProperty(user, "id", "123");
        BeanUtils.setProperty(user, "name", "林沖");
        BeanUtils.setProperty(user, "password", "123456");
        System.out.println(user);
    }

    @Test
    public void testGetProperty() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        User user = new User(1, "林沖", "123456");
        System.out.println(BeanUtils.getProperty(user,"id"));
        System.out.println(BeanUtils.getProperty(user,"name"));
        System.out.println(BeanUtils.getProperty(user,"password"));

    }

    @Test
    public void testCopyProperties() throws InvocationTargetException, IllegalAccessException {
        User user = new User(1, "linchong", "123432");
        User user1 = new User();

        System.out.println("before:" + user1);
        BeanUtils.copyProperties(user1, user);

        System.out.println("after:" + user1);
    }

    @Test
    public void 真香() throws InvocationTargetException, IllegalAccessException {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "2");
        map.put("name", "james");
        map.put("location", "hello");
        map.put("password", "1234354");

        User user = new User();
        System.out.println(user);
        BeanUtils.populate(user, map);
        System.out.println(user);


    }
}

使用BeanUtils封裝工具類:
https://blog.csdn.net/weixin_44009147/article/details/105078346

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章