java中的assert

在java中的Assert是使用的 package org.springframework.util; 这个包中的Assert类, 这个类的方法,可以用于一些校验,如果失败就抛出异常,并可以编辑异常的信息。

常用的方法有

//如果表达式为false,则抛出异常
public static void isTrue(boolean expression, String message) {
		if (!expression) {
			throw new IllegalArgumentException(message);
		}
	}

还可以验证是否为空

//如果对象不为空就抛出异常
public static void isNull(Object object, String message) {
		if (object != null) {
			throw new IllegalArgumentException(message);
		}
	}
//对象为空时抛出异常
public static void notNull(Object object, String message) {
		if (object == null) {
			throw new IllegalArgumentException(message);
		}
	}
//判断集合类是否为空,如果为空则抛出异常,使用的是CollectionUtils的方法
public static void notEmpty(Collection<?> collection, String message) {
		if (CollectionUtils.isEmpty(collection)) {
			throw new IllegalArgumentException(message);
		}
	}

判断对象是都为某个类型

//如果obj对象不为type类型,则抛出异常
public static void isInstanceOf(Class<?> type, Object obj, String message) {
		notNull(type, "Type to check against must not be null");
		if (!type.isInstance(obj)) {
			instanceCheckFailed(type, obj, message);
		}
	}

猜你喜欢

转载自my.oschina.net/u/3045515/blog/1821163