字符数组数据映射转换到实体对象model注解方式 demo

2024-10-09 08:00:56 浏览数 (3)

1.model对象

代码语言:javascript复制
public class UserModel {
    @ColumnAnnotation(index=0)
    private String username;
    @ColumnAnnotation(index=1)
    private String sex;
    @ColumnAnnotation(index=2)
    private String age;
    @ColumnAnnotation(index=3)
    private String address;
    
    
    @Override
    public String toString() {
        return "UserModel [username="   username   ", sex="   sex   ", age="
                  age   ", address="   address   "]";
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}

2.注解

代码语言:javascript复制
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnAnnotation {
    /**
     * 下标
     */
    int index();

}

3.工具类

代码语言:javascript复制
public class IBeanUtils<T> {

    public T fieldSet(T t, String[] dataArray) throws IllegalAccessException {

        if (null == dataArray || dataArray.length == 0) {
            return t;
        }

        Field[] thisFields = t.getClass().getDeclaredFields();

        for (Field f : thisFields) {
            if (f == null) {
                continue;
            }
            if (f.isAnnotationPresent(ColumnAnnotation.class)) {
                ColumnAnnotation columnAnnotation = f.getAnnotation(ColumnAnnotation.class);
                if (columnAnnotation.index() < dataArray.length) {
                    //赋值
                    setVal(t, f, dataArray[columnAnnotation.index()]);
                }
            }
        }
        return t;
    }

    private void setVal(T t, Field f, String data) throws IllegalAccessException {
           f.setAccessible(true);
           f.set(t, data);
    }


    public static void main(String[] args) throws IllegalAccessException {
        String[] dataArray = {"liudehua", "男", "55", "香港","other"};
        UserModel model = new IBeanUtils<UserModel>().fieldSet(new UserModel(), dataArray);
        System.out.println(model.toString());
    }

}

0 人点赞