6

这是一个很简单的问题,我经常在我的项目中使用 com.google.common.base.Preconditions 来验证参数和参数,例如:

Preconditions.checkNotNull(parameter, "message");
Preconditions.checkArgument(parameter > 0, "message");

此代码可能会产生 IllegalArgumentException 或 NPE。但很多时候我需要抛出自己的异常。我怎样才能通过这个图书馆做到这一点?或者,也许你可以建议另一个?先感谢您!

更新:我明白,我可以创建自己的简单实用程序类,但我有兴趣找到现成的解决方案。请让我知道,如果有人知道这是可能的。

4

5 回答 5

7

如果您想抛出自己的异常,只需使用与Preconditions. 这些方法中的每一个都非常简单——与编写自己的方法相比,添加某种“插件”功能以允许指定异常类确实是矫枉过正。

您始终可以使用来源Preconditions作为起点。

于 2013-12-20T15:39:19.200 回答
5

这就是我最终得出的解决方案。它正是我想要的。可能对任何人都有用:

import java.lang.reflect.InvocationTargetException;

// IMPORTANT: parameter exClass must have at least no args constructor and constructor with String param
public class Precondition {

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass) throws T {
    checkArgument(expression, exClass, null);
}

public static <T extends Exception> void checkArgument(boolean expression, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (!expression) {
        generateException(exClass, errorMessage, args);
    }
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass) throws T {
    checkNotNull(reference, exClass, null);
}

public static <T extends Exception> void checkNotNull(Object reference, Class<T> exClass, String errorMessage, Object... args) throws T {
    if (reference == null) {
        generateException(exClass, errorMessage, args);
    }
}

private static <T extends Exception> void generateException(Class<T> exClass, String errorMessage, Object... args) throws T {
    try {
        if (errorMessage == null) {
            throw exClass.newInstance();
        } else {
            throw exClass.getDeclaredConstructor(String.class, Object[].class).newInstance(errorMessage, args);
        }
    } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        e.printStackTrace();
    }
}

}

于 2016-10-26T17:13:19.697 回答
3

您可以将 valid4j 与 hamcrest-matchers 一起使用(在 Maven Central 上以 org.valid4j:valid4j 的形式找到)

对于引发自定义异常的输入验证:

import static org.valid4j.Validation.*;

validate(argument, isValid(), otherwiseThrowing(InvalidException.class));

对于前置条件和后置条件(即断言):

import static org.valid4j.Assertive.*;

require(argument, notNullValue());
...
ensure(result, isValid());

链接:

于 2014-12-01T00:08:57.317 回答
3

您总是可以为自己制作类似的东西(我不知道为什么番石榴的人还没有添加它):

public static void check(final boolean expression, RuntimeException exceptionToThrow) {
    if (!expression) {
        throw checkNotNull(exceptionToThrow);
    }
}

public static void check(final boolean expression, Supplier<? extends RuntimeException> exceptionToThrowSupplier) {
    if (!expression) {
        throw checkNotNull(exceptionToThrowSupplier).get();
    }
}
于 2017-03-31T09:36:53.180 回答
1

异常类型被硬编码到 Preconditions 类中。您将需要实现自己的异常和自己的检查功能。您始终可以在自己的静态类中执行此操作,类似于 Preconditions 的工作方式。

于 2013-12-20T15:40:26.010 回答