首頁 > 軟體

java中給實體物件屬性的空值賦預設值

2022-03-02 13:01:36

給實體物件屬性的空值賦預設值

private final String defaultStr = "";
private final Date defaultDate = new Date();
private final BigDecimal defaultDecimal = new BigDecimal(0);
private final Timestamp defaultTimestamp=new Timestamp(new Date().getTime());
//賦預設值
public void setDefaultValue(Object object) {
    	try {
    		Class clazz = object.getClass();
            Field[] fields = clazz.getDeclaredFields();
            String primaryKey = EntityUtil.getPrimaryKey(currentSession(), object.getClass());
            for(int i=0;i<fields.length;i++){
            	Field field = fields[i];
            	String fieldName = field.getName();
            	Class fieldClass=field.getType();
            	field.setAccessible(true); //設定存取許可權
				if(!fieldName.equals(primaryKey) && isFieldValueNull(fieldName,object)){
					if (fieldClass == Integer.class ) {
						field.set(object, defaultDecimal.intValue());
					}else if (fieldClass == Long.class) {
						field.set(object, defaultDecimal.longValue());
					}else if (fieldClass == Float.class) {
						field.set(object, defaultDecimal.doubleValue());
					}else if (fieldClass == BigDecimal.class) {
						field.set(object, defaultDecimal);
					} else if (fieldClass == Date.class) {
						field.set(object, defaultDate);
					} else if (fieldClass == String.class){
						field.set(object, defaultStr); // 設定值
					} else if (fieldClass == Timestamp.class){
						field.set(object, defaultTimestamp);
					}
            	}else if(fieldName.equals(primaryKey) && isStringFieldValueNull(fieldName,object,fieldClass)){//MySQL,需要對對主鍵做特殊處理
            		field.set(object, null);
            	}
            }
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
    }
 
//判斷欄位是否為空
 private boolean isFieldValueNull(String fieldName, Object object) throws ClassNotFoundException {  
    	boolean isNUll=false;
        try {    
            String firstLetter = fieldName.substring(0, 1).toUpperCase();    
            String getter = "get" + firstLetter + fieldName.substring(1);    
            Method method = object.getClass().getMethod(getter, new Class[] {});    
            Object value = method.invoke(object, new Object[] {});    
            if(value==null){
            	isNUll=true;
            }
            return isNUll;    
        } catch (Exception e) {    
        	 return isNUll;    
        }    
    } 
 
  //判斷主鍵是否為空值
   private boolean isStringFieldValueNull(String fieldName, Object object, Class fieldClass) throws ClassNotFoundException { 
    	boolean isNUll=false;
        try {    
            String firstLetter = fieldName.substring(0, 1).toUpperCase();    
            String getter = "get" + firstLetter + fieldName.substring(1);    
            Method method = object.getClass().getMethod(getter, new Class[] {});    
            Object value = method.invoke(object, new Object[] {}); 
            if(value==null ){
            	isNUll=true;
            }else{
            	if (fieldClass == String.class && StringUtils.isBlank((String)value)) {
            		isNUll=true;
            	}
            }
            return isNUll;    
        } catch (Exception e) {    
        	 return isNUll;    
        }    
    } 
    

給實體類賦預設值通用方法

package com.clamc.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
/**
 * yangzhiwei
 * 使用反射給實體類k賦值(預設值)
 * insert update會報null異常,為空時不能插入和更新
 */
public class ObjInvoke {
    public static Object getObjDefault(Object obj) {
        // 得到類物件
        Class objCla = obj.getClass();
        Field[] fs = objCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            // 設定些屬性是可以存取的
            boolean isStatic = Modifier.isStatic(f.getModifiers());
            if(isStatic){
                continue;
            }
            // 設定些屬性是可以存取的
            f.setAccessible(true);
            try {
                // 得到此屬性的值
                Object val = f.get(obj);
                // 得到此屬性的型別
                String type = f.getType().toString();
                if (type.endsWith("String") && val == null) {
                    // 給屬性設值
                    f.set(obj, "");
                } else if ((type.endsWith("int") ||  type.endsWith("Integer") || type.endsWith("double")) && val == null) {
                    f.set(obj, 0);
                }else if ((type.endsWith("long")|| type.endsWith("Long") )&& val == null){
                    f.set(obj, 0L);
                } else if (type.endsWith("Date") && val == null) {
                    f.set(obj, Date.valueOf("1970-01-01"));
                }else if(type.endsWith("Timestamp") && val == null){
                    f.set(obj, Timestamp.valueOf("1970-01-01 00:00:00"));
                } else if (type.endsWith("BigDecimal") && val == null) {
                    f.set(obj, new BigDecimal(0));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
    public static List getObjDefaultList(List objList) {
        List list=new ArrayList();
        for(Object t:objList){
            list.add(getObjDefault(t));
        }
        return list;
    }
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com