Java tutorial
//package com.java2s; /* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ public class Main { /** * Assert that the provided object is an instance of the provided class. * <p/> * <pre class="code"> * Assert.instanceOf(Foo.class, foo); * </pre> * * @param clazz the required class * @param obj the object to check * @throws IllegalArgumentException if the object is not an instance of clazz * @see Class#isInstance */ public static void isInstanceOf(Class<?> clazz, Object obj) { isInstanceOf(clazz, obj, ""); } /** * Assert that the provided object is an instance of the provided class. * <p/> * <pre class="code"> * Assert.instanceOf(Foo.class, foo); * </pre> * * @param type the type to check against * @param obj the object to check * @param message a message which will be prepended to the message produced by * the function itself, and which may be used to provide context. * It should normally end in a ": " or ". " so that the function * generate message looks ok when prepended to it. * @throws IllegalArgumentException if the object is not an instance of clazz * @see Class#isInstance */ public static void isInstanceOf(Class<?> type, Object obj, String message) { notNull(type, "Type to check against must not be null"); if (!type.isInstance(obj)) { throw new IllegalArgumentException(message + "Object of class [" + (obj != null ? obj.getClass().getName() : "null") + "] must be an instance of " + type); } } /** * Assert that an object is not <code>null</code> . * <p/> * <pre class="code"> * Assert.notNull(clazz, "The class must not be null"); * </pre> * * @param object the object to check * @param message the exception message to use if the assertion fails * @throws IllegalArgumentException if the object is <code>null</code> */ public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } /** * Assert that an object is not <code>null</code> . * <p/> * <pre class="code"> * Assert.notNull(clazz); * </pre> * * @param object the object to check * @throws IllegalArgumentException if the object is <code>null</code> */ public static void notNull(Object object) { notNull(object, "[Assertion failed] - this argument is required; it must not be null"); } }