清除bean中所有非基本数据类型的属性值

利用beanutils清除javabean中所有非基本数据类型的属性值:

 

 

import com.google.gson.Gson;
import lombok.Data;
import org.apache.commons.beanutils.PropertyUtilsBean;
import java.beans.PropertyDescriptor;


@Data
public class RequestParams {
    private String name;
    private Integer age;
    private int d;
    private byte bt;
    private char c;
    private short sd;
    private long ld;
    private float ft;
    private double db;
    private boolean tag;

    /*
    * 设置bean中属性值(基本数据类型,请使用封装类)为null
    */
    public void clear(){
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(this);
            for (int i = 0; i < descriptors.length; i++) {
                String property = descriptors[i].getName();
                if (!"class".equals(property)) {
                    if(!descriptors[i].getPropertyType().isPrimitive()){
                        propertyUtilsBean.setProperty(this,property,null);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        RequestParams requestParams = new RequestParams();
        Gson gson = new Gson();
        requestParams.setName("gh");
        requestParams.setD(19);
        byte b = 101;
        requestParams.setBt(b);
        requestParams.setC('a');
        short s = 20;
        requestParams.setSd(s);
        requestParams.setLd(19L);
        requestParams.setFt(19.1F);
        requestParams.setDb(19.9);
        requestParams.setTag(false);
        requestParams.clear();
        System.out.println(gson.toJson(requestParams));

    }
}

 

posted @ 2018-09-30 12:01  弘文馆校书  阅读(480)  评论(0编辑  收藏  举报