1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util.serviceloader;
17
18 import static com.google.common.base.Preconditions.checkState;
19
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.ServiceLoader;
23
24 import com.google.common.collect.Lists;
25
26 public class ServiceProvider {
27
28
29
30
31
32
33
34 public static <T> T getFirst(Class<T> type) {
35 return getFirst(type, Thread.currentThread().getContextClassLoader());
36 }
37
38
39
40
41
42
43
44 public static <T> T getFirst(Class<T> type, ClassLoader classLoader) {
45 ServiceLoader<T> loader = ServiceLoader.load(type, classLoader);
46 Iterator<T> itr = loader.iterator();
47 checkState(itr.hasNext(), "ServiceLoader could not find a service for type [%s]", type.getCanonicalName());
48 return itr.next();
49 }
50
51
52
53
54 public static <T> List<T> getAll(Class<T> type) {
55 return getAll(type, Thread.currentThread().getContextClassLoader());
56 }
57
58
59
60
61 public static <T> List<T> getAll(Class<T> type, ClassLoader classLoader) {
62 ServiceLoader<T> loader = ServiceLoader.load(type);
63 Iterator<T> itr = loader.iterator();
64 List<T> list = Lists.newArrayList();
65 while (itr.hasNext()) {
66 list.add(itr.next());
67 }
68 return list;
69 }
70
71 }