View Javadoc

1   /*
2    * Grapht, an open source dependency injector.
3    * Copyright 2014-2015 various contributors (see CONTRIBUTORS.txt)
4    * Copyright 2010-2014 Regents of the University of Minnesota
5    *
6    * This program is free software; you can redistribute it and/or modify
7    * it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation; either version 2.1 of the
9    * License, or (at your option) any later version.
10   *
11   * This program is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13   * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14   * details.
15   *
16   * You should have received a copy of the GNU General Public License along with
17   * this program; if not, write to the Free Software Foundation, Inc., 51
18   * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19   */
20  package org.grouplens.grapht.util;
21  
22  import org.grouplens.grapht.InjectionException;
23  import org.grouplens.grapht.InvalidBindingException;
24  import org.grouplens.grapht.reflect.Qualifiers;
25  
26  import java.lang.annotation.Annotation;
27  import java.lang.reflect.Modifier;
28  
29  /**
30   * Utility to organize checks for common assertions, and to throw
31   * appropriately worded exceptions on failure.
32   * 
33   * @author <a href="http://grouplens.org">GroupLens Research</a>
34   */
35  public final class Preconditions {
36      private Preconditions() { }
37  
38      @SuppressWarnings("unchecked")
39      public static void isQualifier(Class<?> type) {
40          if (!Annotation.class.isAssignableFrom(type)) {
41              throw new InvalidBindingException(type, "Type is not an Annotation");
42          }
43          if (!Qualifiers.isQualifier((Class<? extends Annotation>) type)) {
44              throw new InvalidBindingException(type, "Annotation is not annotated with @Qualifier");
45          }
46      }
47      
48      public static void isAssignable(Class<?> source, Class<?> impl) {
49          if (!source.isAssignableFrom(impl)) {
50              throw new InvalidBindingException(impl, "Type is not assignable to " + source);
51          }
52      }
53  
54      public static void notNull(String name, Object value) {
55          if (value == null) {
56              throw new NullPointerException(name + " cannot be null");
57          }
58      }
59      
60      public static void inRange(int value, int min, int max) {
61          if (value < min || value >= max) {
62              throw new IndexOutOfBoundsException(value + " must be in [" + min + ", " + max + ")");
63          }
64      }
65  }