1 | package com.hammurapi.common; |
2 | |
3 | import java.util.Iterator; |
4 | import java.util.Map; |
5 | import java.util.ServiceLoader; |
6 | |
7 | /** |
8 | * Default context uses ServiceLoader to find services in |
9 | * a given classloader and map of bindings. |
10 | * @author Pavel Vlasov |
11 | * |
12 | */ |
13 | public class DefaultContext implements Context { |
14 | |
15 | private ClassLoader classLoader; |
16 | private Map<String, Object> bindings; |
17 | |
18 | /** |
19 | * @param classLoader ClassLoader for services. Can be null. |
20 | * @param bindings Name bindings. Can be null. |
21 | */ |
22 | public DefaultContext(ClassLoader classLoader, Map<String, Object> bindings) { |
23 | this.classLoader = classLoader==null ? this.getClass().getClassLoader() : classLoader; |
24 | this.bindings = bindings; |
25 | } |
26 | |
27 | public Object lookup(String name) { |
28 | return bindings==null ? null : bindings.get(name); |
29 | } |
30 | |
31 | public <T> T lookup(Class<T> serviceClass) { |
32 | ServiceLoader<T> sl = ServiceLoader.load(serviceClass, classLoader); |
33 | Iterator<T> sit = sl.iterator(); |
34 | return sit.hasNext() ? sit.next() : null; |
35 | } |
36 | |
37 | public <T> Iterator<T> lookupAll(Class<T> serviceClass) { |
38 | ServiceLoader<T> sl = ServiceLoader.load(serviceClass, classLoader); |
39 | return sl.iterator(); |
40 | } |
41 | |
42 | } |