| 1 | |
package org.webslinger.resolver; |
| 2 | |
|
| 3 | |
import java.util.HashMap; |
| 4 | |
import java.util.Map; |
| 5 | |
|
| 6 | |
public class BeanResolver<T> extends ContainingResolver<T> { |
| 7 | 6 | private final Map<String, BeanGet<T, ?>> fetchers = new HashMap<String, BeanGet<T, ?>>();; |
| 8 | |
|
| 9 | 6 | public BeanResolver() { |
| 10 | 6 | } |
| 11 | |
|
| 12 | 0 | public BeanResolver(Map<String, BeanGet<T, ?>> fetchers) { |
| 13 | 0 | addAllFetchers(fetchers); |
| 14 | 0 | } |
| 15 | |
|
| 16 | |
public void addFetcher(String name, BeanGet<T, ?> fetcher) { |
| 17 | 61 | fetchers.put(name, fetcher); |
| 18 | 61 | } |
| 19 | |
|
| 20 | |
public void addAllFetchers(Map<String, BeanGet<T, ?>> fetchers) { |
| 21 | 0 | this.fetchers.putAll(fetchers); |
| 22 | 0 | } |
| 23 | |
|
| 24 | |
public boolean contains(T object, String name) { |
| 25 | 0 | return fetchers.containsKey(name); |
| 26 | |
} |
| 27 | |
|
| 28 | |
public Object get(T object, String name) { |
| 29 | 0 | return fetchers.get(name).getValue(object); |
| 30 | |
} |
| 31 | |
|
| 32 | |
public void set(T object, String name, Object value) throws Exception { |
| 33 | 0 | fetchers.get(name).set(object, value); |
| 34 | 0 | } |
| 35 | |
|
| 36 | |
public String[] list(T object) { |
| 37 | |
|
| 38 | 0 | return fetchers.keySet().toArray(new String[fetchers.size()]); |
| 39 | |
} |
| 40 | |
|
| 41 | |
public boolean hasChildren(T object) { |
| 42 | 0 | return true; |
| 43 | |
} |
| 44 | |
|
| 45 | |
public Class getType(T object, String name) { |
| 46 | 0 | return fetchers.get(name).getType(); |
| 47 | |
} |
| 48 | |
|
| 49 | |
public static class BeanGet<T, V> { |
| 50 | |
private String name; |
| 51 | |
private Class<V> type; |
| 52 | |
|
| 53 | 61 | protected BeanGet(String name, Class<V> type) { |
| 54 | 61 | this.name = name; |
| 55 | 61 | this.type = type; |
| 56 | 61 | } |
| 57 | |
|
| 58 | |
public String getName() { |
| 59 | 0 | return name; |
| 60 | |
} |
| 61 | |
|
| 62 | |
public Class<V> getType() { |
| 63 | 0 | return type; |
| 64 | |
} |
| 65 | |
|
| 66 | |
public V getValue(T object) { |
| 67 | 0 | throw new UnsupportedOperationException(getName()); |
| 68 | |
} |
| 69 | |
|
| 70 | |
protected void set(T object, Object value) throws Exception { |
| 71 | 0 | setValue(object, type.cast(value)); |
| 72 | 0 | } |
| 73 | |
|
| 74 | |
public void setValue(T object, V value) throws Exception { |
| 75 | 0 | throw new UnsupportedOperationException(getName()); |
| 76 | |
} |
| 77 | |
} |
| 78 | |
} |