判断Object是否为空的通用方法

1、判断Object是否有空(类型包含CharSequence、Number、Collection、Map、Object[])

public static boolean checkObject(Object object){
   if(object==null){
	   return true;
   }
   if(object instanceof CharSequence){
	   return ((CharSequence)object).length() == 0;
   }
   if(object instanceof Collection){
	   return ((Collection)object).isEmpty();
   }
   if (object instanceof Map){
	   return ((Map)object).isEmpty();
   }
   if(object instanceof Object[]){
	   return ((Object[])object).length == 0;
   }
	return false;
}

2、判断多个参数是否有空

public static boolean checkObjects(Object... objects){
	for (Object obj:objects) {
		if(checkObject(obj)){
			return true;
		}
	}
	return false;
}

3、判断对象的所有属性是否有空

public static  boolean checkAll(T model) throws IllegalAccessException {
	List fields = getAllField(model);
	for (Field field:fields) {
		field.setAccessible(true);
		Object object = field.get(model);
		if(checkObject(object)){
			return true;
		}
	}
	return false;
}

 另一种方式获取属性值

public static  boolean checkAllParam(T model) {
	List fields = getAllField(model);
	for (Field field:fields) {
		String name = field.getName().substring(0,1).toUpperCase()+field.getName().substring(1);
		try {
			Method method = model.getClass().getMethod("get"+name);
			Object object = method.invoke(model);
			if(checkObject(object)){
				return true;
			}
		} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	return false;
}

另附获取到对象的所有字段(包括所有继承的父类)

private static List getAllField(Object model){
        Class clazz = model.getClass();
        List fields = new ArrayList<>();
        while (clazz!=null){
            fields.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

 

你可能感兴趣的:(Java,java,object)