BeanUtils_BeanUtils

2022-10-01 15:20:37 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

1. beanUtils工程

1.工程目录

2.需要的jar包: commons-beanutils-1.9.3.jar commons-collections-3.2.2.jar commons-logging-1.2.jar 3.转换器 DateConverter.java:

代码语言:javascript复制
package com.my.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.AbstractConverter;
import org.apache.commons.beanutils.converters.DateTimeConverter;

public class DateConverter<T> extends org.apache.commons.beanutils.converters.DateTimeConverter { 
   
    private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    @Override
    /** * arg0 转换的目的类型 * arg1 需要转换的数值 * @return 返回转换后的数值 */
    public <T> T convert(Class<T> clz, Object value) {
        //1.转换的类型是否符合要求
        if(Date.class!=clz) {
            return null;
        }
        if(value instanceof String) {
            try {
                return (T) sdf.parse((String)value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected Object convertArray(Object arg0) {
        return super.convertArray(arg0);
    }

    @Override
    protected Class<?> getDefaultType() {
        return null;
    }

}

PointConvert.java:

代码语言:javascript复制
package com.my.model;

import org.apache.commons.beanutils.converters.AbstractConverter;

public class PointConvert<T> extends AbstractConverter{ 
   

    @Override
    public <T> T convert(Class<T> clz, Object value) {
        if(Point.class!=clz) {
            return null;
        }
        if(value instanceof String) {
            String val=(String)value;
            String[] strArray=val.split(",");
            if(strArray.length<2) {
                return null;
            }
            int x=0, y=0;
            try {
                x=Integer.parseInt(strArray[0]);
                y=Integer.parseInt(strArray[1]);
            }catch(NumberFormatException e) {
                e.printStackTrace();
            }
            return (T) new Point(x, y);
        }
        return null;
    }

    @Override
    protected <T> T convertToType(Class<T> arg0, Object arg1) throws Throwable {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class<?> getDefaultType() {
        // TODO Auto-generated method stub
        return null;
    }

}

4.model类 Point.java:

代码语言:javascript复制
package com.my.model;

public class Point{ 
   
    private int x;
    private int y;
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public Point() {
    }
    @Override
    public String toString() {
        return "Point [x="   x   ", y="   y   "]";
    }
}

User.java:

代码语言:javascript复制
package com.my.model;
import java.util.Date;
public class User { 

private int id;
private String username;
private int age;
private String password;
private Date born;
private Point point;
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBorn() {
return born;
}
public void setBorn(Date born) {
this.born = born;
}
public User(int id, String username, int age, String password, Date born) {
super();
this.id = id;
this.username = username;
this.age = age;
this.password = password;
this.born = born;
}
public User() {
}
public User(int id, String username, int age, String password, Date born, Point point) {
this.id = id;
this.username = username;
this.age = age;
this.password = password;
this.born = born;
this.point = point;
}
@Override
public String toString() {
return "User [id="   id   ", username="   username   ", age="   age   ", password="   password   ", born="
  born   ", point="   point   "]";
}
}

5.Junit测试类: TestBeanUtils.java:

代码语言:javascript复制
package com.my.test;
import static org.junit.Assert.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.junit.After;
import org.junit.Test;
import com.my.model.DateConverter;
import com.my.model.Point;
import com.my.model.PointConvert;
import com.my.model.User;
public class TestBeanUtils { 

@Test
public void test01() {
User user=new User();
User user2=new User();
String key="username";
String value="张三";
try {
BeanUtils.copyProperty(user, key, value);
BeanUtils.copyProperty(user, "age", 1);
BeanUtils.copyProperty(user, "age", "20");
BeanUtils.copyProperty(user, "dass", value);
//DateConverter does not support default String to 'Date' conversion.
//这时候需要自己定义相应的转换器来完成转换
//定义转换器的步骤:
//1创建一个类让其实现Converter接口.
//2.覆盖convert方法,在这个方法中实现转换
//3.拷贝属性之前注册转换器
//注册Date类型的转换器DateConverter
ConvertUtils.register(new DateConverter<>(), Date.class);
ConvertUtils.register(new PointConvert<>(), Point.class);
BeanUtils.copyProperty(user, "born", "1997-2-20");
BeanUtils.copyProperty(user, "point", "10,12");
//BeanUtils.copyProperty(user, "born", new Date());
BeanUtils.copyProperties(user2, user);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(user);
System.out.println(user2);
}
}

运行结果:

代码语言:javascript复制
User [id=0, username=张三, age=20, password=null, born=Thu Feb 20 00:00:00 CST 1997, point=Point [x=10, y=12]]
User [id=0, username=张三, age=20, password=null, born=null, point=null]

2.beanUtils封装请求参数

代码语言:javascript复制
/** * * @param clz,目标类的类型 * @param request,请求 * @return 目标类型的对象 */
public static Object setParam(Class<?> clz, HttpServletRequest request) {
Map<String, String[]> paramMap=request.getParameterMap();
Set<String> strSet=paramMap.keySet();
Object object=null;
try {
object=clz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
for(String str: strSet) {
LogUtil.printLog(str ": " paramMap.get(str)[0] " |" object);
try {
String[] paramValue=paramMap.get(str);
if(paramValue.length>1) {
BeanUtils.setProperty(object, str, paramValue);
}else {
BeanUtils.setProperty(object, str, paramValue[0]);
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
return object;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/194740.html原文链接:https://javaforall.cn

0 人点赞