1 package com.lexicalscope.fluentreflection.bean;
2
3 import static com.lexicalscope.fluentreflection.FluentReflection.type;
4 import static com.lexicalscope.fluentreflection.ReflectionMatchers.*;
5 import static com.lexicalscope.fluentreflection.dynamicproxy.FluentProxy.dynamicProxy;
6
7 import java.lang.reflect.Proxy;
8 import java.util.Map;
9
10 import com.lexicalscope.fluentreflection.FluentClass;
11 import com.lexicalscope.fluentreflection.dynamicproxy.Implementing;
12 import com.lexicalscope.fluentreflection.dynamicproxy.MethodBody;
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 public class MapBean {
31 public static <T> T bean(final Class<T> klass, final Map<String, Object> map) {
32 return bean(type(klass), map);
33 }
34
35 public static <T> T bean(final FluentClass<T> klass, final Map<String, Object> map) {
36 return dynamicProxy(new Implementing<T>(klass) {
37 private final Object identity = new Object();
38 {
39 whenProxying(isHashCodeMethod())
40 .execute(new MethodBody() {
41 @Override public void body() throws Throwable {
42 returnValue(identity.hashCode());
43 }
44 });
45
46 whenProxying(isEqualsMethod())
47 .execute(new MethodBody() {
48 @Override public void body() throws Throwable {
49 final Object that = args()[0];
50 returnValue(Proxy.isProxyClass(that.getClass())
51 && that == proxy());
52 }
53 });
54
55 whenProxying(isToStringMethod()).execute(new MethodBody() {
56 @Override public void body() throws Throwable {
57 returnValue(klass.name() + " " + map.toString());
58 }
59 });
60
61 whenProxying(
62 isGetter().and(
63 hasType(boolean.class).or(
64 hasType(Boolean.class)))).execute(new MethodBody() {
65 @Override public void body() {
66 returnValue(map.containsKey(method().property()));
67 }
68 });
69
70 whenProxying(isExistence()).execute(new MethodBody() {
71 @Override public void body() {
72 returnValue(map.containsKey(method().property()));
73 }
74 });
75
76 whenProxying(isQuery()).execute(new MethodBody() {
77 @Override public void body() {
78 returnValue(map.get(method().property()));
79 }
80 });
81
82 whenProxying(isMutator()).execute(new MethodBody() {
83 @Override public void body() {
84 map.put(method().property(), args()[0]);
85 }
86 });
87 }
88 });
89 }
90 }