java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 给实体对象属性的空值赋默认值

java中给实体对象属性的空值赋默认值

作者:我觉得OK

这篇文章主要介绍了java中给实体对象属性的空值赋默认值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

给实体对象属性的空值赋默认值

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;
    }
}

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

您可能感兴趣的文章:
阅读全文