Guava Preconditions的自定义异常

max*_*axi 3 java preconditions guava

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

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

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

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

Jon*_*eet 6

如果你想抛出自己的异常,只需用类似的方法创建自己的类Preconditions.这些方法中的每一种都非常简单 - 添加某种"插件"功能以允许指定异常类与编写自己的方法相比实际上是过度的.

您始终可以使用Preconditions作为起点.


max*_*axi 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

}