001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.mybatisflex.core.exception; 018 019import com.mybatisflex.core.exception.locale.LocalizedFormats; 020 021import java.util.Collection; 022import java.util.Map; 023 024/** 025 * 断言。 026 * 027 * @author 王帅 028 * @author michael 029 * 030 * @since 2023-07-08 031 */ 032public final class FlexAssert { 033 034 private FlexAssert() { 035 } 036 037 /** 038 * 断言对象不为空,如果为空抛出异常,并指明哪个对象为空。 039 * 040 * @param obj 对象 041 * @param param 错误消息参数 042 * @throws MybatisFlexException 如果对象为空,抛出此异常。 043 */ 044 public static void notNull(Object obj, String param) { 045 if (obj == null) { 046 throw FlexExceptions.wrap(LocalizedFormats.OBJECT_NULL, param); 047 } 048 } 049 050 051 /** 052 * 断言 Map 集合不为 {@code null} 或者空集合,如果为空则抛出异常,并指明为什么不允许为空集合。 053 * 054 * @param map Map 集合 055 * @param param 错误消息参数 056 * @throws MybatisFlexException 如果集合为空,抛出此异常。 057 */ 058 public static void notEmpty(Map<?, ?> map, String param) { 059 if (map == null || map.isEmpty()) { 060 throw FlexExceptions.wrap(LocalizedFormats.MAP_NULL_OR_EMPTY, param); 061 } 062 } 063 064 /** 065 * 断言集合不为 {@code null} 或者空集合,如果为空则抛出异常,并指明为什么不允许为空集合。 066 * 067 * @param collection 集合 068 * @param param 错误消息参数 069 * @throws MybatisFlexException 如果集合为空,抛出此异常。 070 */ 071 public static void notEmpty(Collection<?> collection, String param) { 072 if (collection == null || collection.isEmpty()) { 073 throw FlexExceptions.wrap(LocalizedFormats.MAP_NULL_OR_EMPTY, param); 074 } 075 } 076 077 /** 078 * 断言数组不为 {@code null} 或者空数组,如果为空则抛出异常,并指明为什么不允许为空数组。 079 * 080 * @param array 数组 081 * @param param 错误消息参数 082 * @throws MybatisFlexException 如果数组为空,抛出此异常。 083 */ 084 public static <T> void notEmpty(T[] array, String param) { 085 if (array == null || array.length == 0) { 086 throw FlexExceptions.wrap(LocalizedFormats.ARRAY_NULL_OR_EMPTY, param); 087 } 088 } 089 090 /** 091 * 断言传入的数组内容不能为 null 或者 空 092 */ 093 public static <T> void assertAreNotNull(T[] elements, String msg, Object params) { 094 if (elements == null || elements.length == 0) { 095 throw FlexExceptions.wrap(msg, params); 096 } 097 for (T element : elements) { 098 if (element == null) { 099 throw FlexExceptions.wrap(msg, params); 100 } 101 } 102 } 103 104}