package cn.autoform.util.tool; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Collection; import java.util.Map; import java.util.Objects; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class ObjectUtil { /** * 为空的 * @param obj * @return */ @SuppressWarnings("rawtypes") public static boolean empty(Object obj) { if (obj == null){ return true; } if (obj instanceof Number && ((Number)obj).doubleValue() == 0.0){ return true; } if (obj instanceof String && StringUtils.isBlank(obj.toString())){ return true; } if (obj.getClass().isArray() && Array.getLength(obj)==0){ return true; } if (obj instanceof Collection && CollectionUtils.isEmpty((Collection)obj)){ return true; } if (obj instanceof Map && ((Map)obj).isEmpty()){ return true; } if (Objects.equals("{}", JSONTool.toJson(obj))){ return true; } return false; } /** * 不为空的 * @param obj * @return */ public static boolean notEmpty(Object obj){ return !empty(obj); } /** * 匹配一个 * @param obj1 * @param objs * @return */ public static boolean or(Object obj1, Object... objs) { for(Object obj:objs){ if(Objects.equals(obj, obj1)){ return true; } } return false; } public static boolean and(Object obj1, Object... objs){ if(empty(objs)) return empty(obj1) ? true : false; return Objects.equals(objs.length, andSize(obj1, objs)); } /** * 匹配个数 * @param obj1 * @param objs * @return */ public static int andSize(Object obj1, Object... objs){ int size = 0; if(empty(objs)) return size; for(Object obj:objs){ if(Objects.equals(obj, obj1)){ size ++; } } return size; } /** * obj转byte * @param obj * @return */ public static byte[] objectToByte(Serializable obj) { Objects.requireNonNull(obj); byte[] bytes = null; try ( ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo);){ oo.writeObject(obj); bytes = bo.toByteArray(); } catch (Exception e) { log.error(e.getMessage(), e); } return bytes; } /** * byte转obj * @param obj * @return */ @SuppressWarnings("unchecked") public static T byteToObject(byte[] bytes, Class clazz) { Objects.requireNonNull(bytes); Objects.requireNonNull(clazz); T obj = null; try ( ByteArrayInputStream bi = new ByteArrayInputStream(bytes); ObjectInputStream oi = new ObjectInputStream(bi);){ obj = (T) oi.readObject(); } catch (Exception e) { log.error(e.getMessage(), e); } return obj; } }