JavaBean字段如何防止非空赋值

时间:2021-09-04 02:41:26

JavaBean字段防止非空赋值

前言

工具类制作起因,有时候项目中出一点点错误,在所难免,经常,有些地方的字段是String,但是到了其他地方是Long,Date,Interger,BigDecimal,这个时候每次都需要判断下是否为空,否则就会在New BigDecimal(string)等中转化失败,报空指针。 如果字段很多,简直太恶心了。

这里日期是最恶心心,日期分为Date类型和String类型 转化为Date

举例

?
1
2
3
if(string!=null){
   date.setBigValue(new BigDecimal(string));
 }

1、JavaBean制作

1.1、初始JavaBean User

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class User {
 /**
     * 如果属性类型为基本数据类型,则会有默认值
     * 影响正确判断,请特别注意
     */
//  private int age;
    private Integer age;
    private String name;
    private String gender;
    private BigDecimal bigDecimal;
    private Date date ;
    private Long longvalue;   
    private String dateStr ; //注意这里是String类型的日期 例如 2018-12-09 00:00:00
    get set……

1.2、被赋值的JavaBean

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 作者 :HealerJean
 * 日期 :2018/12/13  上午11:03.
 * 类描述:
 */
public class UserNow {
    private String nameNow;
    private String genderNow;
    private Integer ageNow;
    private BigDecimal bigDecimalNow ;
    private Date dateNow ;
    private Long longvalueNow;
    private Date dateStrNow ; //注意这里是Date类型
get set……

2、利用反射实现工具类

需要注意的是,下面的日期,在我们通过反射获取到值的时候,它打印出来的是英文日期串,我们需要对他进行一个转化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.hlj.IgnoreNullBean;
import org.junit.platform.commons.util.StringUtils;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
 * 作者 :HealerJean
 * 日期 :2018/12/13  上午10:55.
 * 类描述 防止非空字段,在类似于 new BigDecimal(string))中进行报错
 */
public class JavaBeanUtil {
    /**
     *
     * @param object 原始数据JavaBean
     * @param originFieldName 原始数据 字段名字 比如:name
     * @param newObject 新复制的JavaBean
     * @param newFilldName 新赋值的字段名字 比如 nameNow
     * @param dateFormat 如果是date类型的日期,
     *                   1、传入的是String字符串'2018-12-09'   则需要传入相应Fromat格式 yyyy-MM-dd HH:mm:ss
     *                   2、如果是标准高的date类型,那么.toString之后是 -> Fri Dec 14 19:00:07 CST 2018, 则设置为null
     */
    public static  void setFieldValue(Object object,String originFieldName,Object newObject,String newFilldName,String ...dateFormat) {
        try {
            Field field = object.getClass().getDeclaredField(originFieldName);
            field.setAccessible(true);
            Field newfield = newObject.getClass().getDeclaredField(newFilldName);
            newfield.setAccessible(true);
            String newfieldType=newfield.getGenericType().toString();
            if (field.get(object) != null && StringUtils.isNotBlank(field.get(object).toString())) {
                String value = field.get(object).toString();
                System.out.println(value);
                switch (newfieldType){
                    case "class java.lang.Integer":
                        newfield.set(newObject, Integer.valueOf(value));
                        break;
                    case "class java.lang.Long":
                        newfield.set(newObject, Long.valueOf(value));
                        break;
                    case "class java.math.BigDecimal":
                        newfield.set(newObject, new BigDecimal(Double.valueOf(value)) );
                        break;
                    case "class java.util.Date":
                        Date  date = null;
                        if(dateFormat!=null&&dateFormat.length>0){
                            date = new SimpleDateFormat(dateFormat[0]).parse(value);
                            newfield.set(newObject, date);
                        }else {
                              date=new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(value);
                        }
                        newfield.set(newObject, date);
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3、测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.hlj.IgnoreNullBean;
import com.hlj.IgnoreNullBean.data.User;
import com.hlj.IgnoreNullBean.data.UserNow;
import java.math.BigDecimal;
import java.util.Date;
/**
 * 作者 :HealerJean
 * 日期 :2018/12/13  上午10:54.
 * 类描述:
 */
public class TestMain {
    public static void main(String[] args) {
        User user = new User();
        user.setAge(25);
        user.setBigDecimal(new BigDecimal(10.21));
        user.setDate(new Date());
        user.setLongvalue(100L);
        user.setDateStr("2018-12-09 00:00:00");
        UserNow userNow = new UserNow() ;
        JavaBeanUtil.setFieldValue(user,"age",userNow,"ageNow");
        System.out.println("ageNow:"+userNow.getAgeNow());
        JavaBeanUtil.setFieldValue(user,"bigDecimal",userNow,"bigDecimalNow");
        System.out.println("bigDecimalNow:"+userNow.getBigDecimalNow());
        JavaBeanUtil.setFieldValue(user,"date",userNow,"dateNow");
        System.out.println("dateNow:"+ userNow.getDateNow());
        JavaBeanUtil.setFieldValue(user,"longvalue",userNow,"longvalueNow");
        System.out.println("longvalueNow:"+userNow.getLongvalueNow());
        JavaBeanUtil.setFieldValue(user,"dateStr",userNow,"dateStrNow","yyyy-MM-dd HH:mm:ss");
        System.out.println("dateStrNow:"+userNow.getDateStrNow());
    }
ageNow:25
bigDecimalNow:10.21000000000000085265128291212022304534912109375
dateNow:Fri Dec 14 19:27:07 CST 2018
longvalueNow:100
dateStrNow:Sun Dec 09 00:00:00 CST 2018

判断javabean是否非空,并给前台报出错误信息

1、工具类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.duodian.youhui.admin.utils;
import com.duodian.youhui.admin.Exceptions.AppException;
import com.duodian.youhui.entity.db.taobao.TaobaoWechat;
import java.lang.reflect.Field;
/**
 * 作者 :HealerJean
 * 日期 :2019/1/24  下午4:30.
 * 类描述:判断是否为空 或者是null 工具
 */
public class JudgeNullUtils {
    public static boolean isNull(Object object,String ... fieldName){
        try {
            for (int i = 0; i < fieldName.length; i++) {
                Field field = null;
                    field = object.getClass().getDeclaredField(fieldName[i]);
                field.setAccessible(true);//暴力反射,获取获取数据
                if(field.get(object)==null){
                    //返回flase或者直接抛出异常,根据我们的情况而定
                    throw  new AppException(fieldName[i]+"不能为空");
                }
            }
            return true ;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false ;
    }
}

2、catch捕获

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@ApiOperation(value = "添加淘宝营销总代理",
        notes = "添加淘宝营销总代理",
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE,
        response = ResponseBean.class
)
@ResponseBody
@GetMapping("addEsWechat")
public ResponseBean addEsWechat(TaobaoEsWechat taobaoWechat ){
    try {
        JudgeNullUtils.isNull(taobaoWechat,"code","status");
        return ResponseBean.buildSuccess(taobaoEsWechatService.addTaobaoEsWechat(taobaoWechat));
    } catch (AppException e) {
        ExceptionLogUtils.log(e, this.getClass());
        return ResponseBean.buildFailure(e.getCode(),e.getMessage());
    } catch (Exception e) {
        ExceptionLogUtils.log(e, this.getClass());
        return ResponseBean.buildFailure(e.getMessage());
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u012954706/article/details/84985935