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 com.google.common.base.Supplier;
23  
24  import javax.annotation.Nonnull;
25  import javax.annotation.Nullable;
26  import javax.inject.Provider;
27  
28  /**
29   * Utility methods for providers.
30   *
31   * @since 0.6
32   * @author <a href="http://grouplens.org">GroupLens Research</a>
33   */
34  public final class Providers {
35      private Providers() {}
36  
37      public static <T> Provider<T> of(@Nonnull T object) {
38          return new InstanceProvider<T>(object, object.getClass());
39      }
40  
41      public static <T> Provider<T> of(@Nullable T object, Class<?> type) {
42          return new InstanceProvider<T>(object, type);
43      }
44  
45      public static <T> Provider<T> memoize(@Nonnull Provider<T> inner) {
46          return new MemoizingProvider<T>(inner);
47      }
48  
49      /**
50       * Convert a supplier to a provider.
51       * @param supplier The supplier.
52       * @param type The supplier's return type (to help the injector).
53       * @param <T> The type returned from the supplier.
54       * @return A provider.
55       */
56      public static <T> Provider<T> fromSupplier(final Supplier<T> supplier, final Class<T> type) {
57          return new TypedProvider<T>() {
58              @Override
59              public Class<?> getProvidedType() {
60                  return type;
61              }
62  
63              @Override
64              public T get() {
65                  return supplier.get();
66              }
67          };
68      }
69  }