001/* 002 * Copyright (c) 2022-2025, 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 */ 016package com.mybatisflex.core.exception; 017 018import com.mybatisflex.core.exception.locale.LocalizedFormats; 019 020import java.util.Collection; 021import java.util.Map; 022 023/** 024 * 断言。 025 * 026 * @author 王帅 027 * @author michael 028 * 029 * @since 2023-07-08 030 */ 031public final class FlexAssert { 032 033 private FlexAssert() { 034 } 035 036 /** 037 * 断言对象不为空,如果为空抛出异常,并指明哪个对象为空。 038 * 039 * @param obj 对象 040 * @param param 错误消息参数 041 * @throws MybatisFlexException 如果对象为空,抛出此异常。 042 */ 043 public static void notNull(Object obj, String param) { 044 if (obj == null) { 045 throw FlexExceptions.wrap(LocalizedFormats.OBJECT_NULL, param); 046 } 047 } 048 049 050 /** 051 * 断言 Map 集合不为 {@code null} 或者空集合,如果为空则抛出异常,并指明为什么不允许为空集合。 052 * 053 * @param map Map 集合 054 * @param param 错误消息参数 055 * @throws MybatisFlexException 如果集合为空,抛出此异常。 056 */ 057 public static void notEmpty(Map<?, ?> map, String param) { 058 if (map == null || map.isEmpty()) { 059 throw FlexExceptions.wrap(LocalizedFormats.MAP_NULL_OR_EMPTY, param); 060 } 061 } 062 063 /** 064 * 断言集合不为 {@code null} 或者空集合,如果为空则抛出异常,并指明为什么不允许为空集合。 065 * 066 * @param collection 集合 067 * @param param 错误消息参数 068 * @throws MybatisFlexException 如果集合为空,抛出此异常。 069 */ 070 public static void notEmpty(Collection<?> collection, String param) { 071 if (collection == null || collection.isEmpty()) { 072 throw FlexExceptions.wrap(LocalizedFormats.MAP_NULL_OR_EMPTY, param); 073 } 074 } 075 076 /** 077 * 断言数组不为 {@code null} 或者空数组,如果为空则抛出异常,并指明为什么不允许为空数组。 078 * 079 * @param array 数组 080 * @param param 错误消息参数 081 * @throws MybatisFlexException 如果数组为空,抛出此异常。 082 */ 083 public static <T> void notEmpty(T[] array, String param) { 084 if (array == null || array.length == 0) { 085 throw FlexExceptions.wrap(LocalizedFormats.ARRAY_NULL_OR_EMPTY, param); 086 } 087 } 088 089 /** 090 * 断言传入的数组内容不能为 null 或者 空 091 */ 092 public static <T> void assertAreNotNull(T[] elements, String msg, Object params) { 093 if (elements == null || elements.length == 0) { 094 throw FlexExceptions.wrap(msg, params); 095 } 096 for (T element : elements) { 097 if (element == null) { 098 throw FlexExceptions.wrap(msg, params); 099 } 100 } 101 } 102 103}