Java 是否可以从assert方法引发自定义异常?

Java 是否可以从assert方法引发自定义异常?,java,assert,Java,Assert,我必须验证一个包含大约40个必填字段的请求 我希望通过避免经典的if(field1==null)抛出新的XXException(“msg”) 例如,我有以下代码: if (caller == null) { // Caller cannot be empty throw new CallerErrorException(new CallerError("", "incorrect caller")); } if (person == null) { // Person c

我必须验证一个包含大约40个必填字段的请求

我希望通过避免经典的
if(field1==null)抛出新的XXException(“msg”)

例如,我有以下代码:

if (caller == null)
{
    // Caller cannot be empty
    throw new CallerErrorException(new CallerError("", "incorrect caller"));
}
if (person == null)
{
    // Person cannot be empty
    throw new PersonErrorException(new CustomerError("", "incorrect customer"));
}
if (module == null)
{
    // Module cannot be empty
    throw new ModuleErrorException(new ModuleError("", "module must be X"));
}
正如您所看到的,根据哪个字段为null,将随自定义消息引发特定的自定义异常

所以,我想要这样的东西:

assertNotEquals(call, null, new CallerErrorException(new CallerError("", "incorrect caller")));
assertNotEquals(person, null, new PersonErrorException(new CustomerError("", "incorrect caller")));
assertNotEquals(module , null, new ModuleErrorException(new ModuleError("", "incorrect caller")));
是否有内置功能允许我这样做


我知道assertEquals会生成assertionError,但我需要生成我的自定义异常。

内置的任何东西都不适用于此,但您当然可以编写自己的:

static void checkNull(Object val, Class exClass, Class innerClass, String arg1, String arg2)
    throws Exception {
    if (val != null) {
        return;
    }
    Object inner = innerClass
        .getDeclaredConstructor(String.class, String.class)
        .newInstance(arg1, arg2);
    throw (Exception)exClass
        .getDeclaredConstructor(innerClass) // This may need to be changed 
        .newInstance(inner);
}
上面的代码根据需要使用反射来构建异常对象。如果需要内部错误对象的超类来匹配正确的类型,则可能必须更改传递给异常对象构造函数的类型

现在,您可以按如下方式编写代码:

checkNull(caller, CallerErrorException.class, CallerError.class, "", "incorrect caller");
checkNull(person, PersonErrorException.class, PersonError.class, "", "incorrect person");

这种方法可以避免在不需要抛出异常对象的情况下创建异常对象。

您可以使用自己的函数:

public static <T extends Throwable> void throwIfNotEqual(Object o1, Object o2, T exception) throws T {
    if (o1 != o2) {
        throw exception;
    }
}
公共静态void throwIfNotEqual(对象o1、对象o2、T异常)抛出T{
如果(o1!=o2){
抛出异常;
}
}
更新 如果将此方法与您结合使用,则您可以仅在需要时创建异常,并且仍然比“抛出异常”更精确。签字将是:

static <T extends Throwable> void checkNull(Object val, Class<T> exClass, Class innerClass, String arg1, String arg2)
    throws T, ReflectiveOperationException
static void checkNull(对象val、类惊叹、类innerClass、字符串arg1、字符串arg2)
抛出T,ReflectiveOperationException

使用JAVA 8的简单实现

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

class Scratch {
    public static void main(String[] args) {

        List<Integer> inputs = Arrays.asList(1,2,3,4);
        AssertUtils.check(inputs, input -> inputs.contains(5), new RuntimeException("Element 5 doesn't exist"));

        String nullString = null;
        AssertUtils.check(nullString, Objects::nonNull, new RuntimeException("Input is null"));
    }

}

/**
 * Assert to throw Custom exceptions rather than default IllegalArgumentException by {@link
 * org.springframework.util.Assert}. 
 * Usage:
 * AssertUtil.check(input, predicate, customException)
 * Example:
 * List<Integer> inputs = Arrays.asList(1,2,3,4);
        AssertUtils.check(inputs, input -> inputs.contains(5), new RuntimeException("Element 5 doesn't exist"));
 * @param <T>
 */
class AssertUtils<T> {

    public static <T> void check(T input, Predicate<T> predicate, RuntimeException runtimeException) {
        if (!predicate.test(input)) {
            throw runtimeException;
        }
    }
}
导入java.util.array;
导入java.util.List;
导入java.util.function.Predicate;
课堂擦伤{
公共静态void main(字符串[]args){
列表输入=数组.asList(1,2,3,4);
检查(输入,输入->输入包含(5),新的运行时异常(“元素5不存在”);
字符串nullString=null;
检查(空字符串,对象::非空,新运行时异常(“输入为空”);
}
}
/**
*断言通过{@link引发自定义异常,而不是默认的IllegalArgumentException
*org.springframework.util.Assert}。
*用法:
*AssertUtil.check(输入、谓词、自定义异常)
*例如:
*列表输入=数组.asList(1,2,3,4);
检查(输入,输入->输入包含(5),新的运行时异常(“元素5不存在”);
*@param
*/
类别资产{
公共静态无效检查(T输入、谓词谓词、RuntimeException RuntimeException){
if(!谓词测试(输入)){
抛出运行时异常;
}
}
}

您是否因为编写单元测试而谈论
assertNotEquals
。不,我不是在写单元测试,它是为有大量参数的后端入口点编写的。