在代码编写时经常需要判断条件并抛出异常,本程序使用类反射机制抛出异常,减少new操作。
package common.utils;
/** 公共类
* @create: 2023/11/27
* @Description:
* @FileName: CommonUtil
*/
public class CommonUtil {
private CommonUtil() {}
/** 如果 !condition,抛出 cls 类型的异常,携带 message
* @Description:
* @date: 2023/11/27
* @param cls 异常类
* @param condition 条件
* @param message 不满足条件时信息
* @return: void
*/
public static <E extends Throwable> void require(Class<E> cls, boolean condition, String message) {
try {
if (!condition) {
throw cls.getConstructor(String.class).newInstance(message);
}
} catch (Throwable t) {
// RuntimeException 不可缺少
throw CommonUtil.<RuntimeException>throwEX(t);
}
}
/** 参考 @{@link lombok.SneakyThrows} 注解,
* 可将必检异常转换为免检异常
* @Description:
* @date: 2023/11/27
* @param t 异常对象
* @return: E
*/
private static <E extends Throwable> E throwEX(Throwable t) throws E {
throw (E) t;
}
}
测试:
package common.utils;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
class CommonUtilTest {
@Test
void require() {
Assert.assertThrows(Throwable.class, () -> CommonUtil.require(Throwable.class, false, null));
Assert.assertThrows(Error.class, () -> CommonUtil.require(Error.class, false, null));
Assert.assertThrows(RuntimeException.class, () -> CommonUtil.require(RuntimeException.class, false, null));
Assert.assertThrows(Exception.class, () -> CommonUtil.require(Exception.class, false, null));
CommonUtil.require(IllegalStateException.class, false, "非法状态");
}
}