1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.supercsv.util;
17
18 import static org.supercsv.util.ReflectionUtils.GET_PREFIX;
19 import static org.supercsv.util.ReflectionUtils.SET_PREFIX;
20
21 import java.lang.reflect.InvocationHandler;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Proxy;
24 import java.util.HashMap;
25 import java.util.Map;
26
27
28
29
30
31
32
33
34
35
36
37
38 public final class BeanInterfaceProxy implements InvocationHandler {
39
40 private final Map<String, Object> beanState = new HashMap<String, Object>();
41
42
43 private BeanInterfaceProxy() {
44 }
45
46
47
48
49
50
51
52
53
54
55
56
57 public static <T> T createProxy(final Class<T> proxyInterface) {
58 if( proxyInterface == null ) {
59 throw new NullPointerException("proxyInterface should not be null");
60 }
61 return proxyInterface.cast(Proxy.newProxyInstance(proxyInterface.getClassLoader(),
62 new Class[] { proxyInterface }, new BeanInterfaceProxy()));
63 }
64
65
66
67
68
69
70
71
72
73
74
75
76
77 public Object invoke(final Object proxy, final Method method, final Object[] args) {
78
79 final String methodName = method.getName();
80
81 if( methodName.startsWith(GET_PREFIX) ) {
82
83 if( method.getParameterTypes().length > 0 ) {
84 throw new IllegalArgumentException(String.format(
85 "method %s.%s() should have no parameters to be a valid getter", method.getDeclaringClass()
86 .getName(), methodName));
87 }
88
89
90 return beanState.get(methodName.substring(GET_PREFIX.length()));
91
92 } else if( methodName.startsWith(SET_PREFIX) ) {
93
94 if( args == null || args.length != 1 ) {
95 throw new IllegalArgumentException(String.format(
96 "method %s.%s() should have exactly one parameter to be a valid setter", method
97 .getDeclaringClass().getName(), methodName));
98 }
99
100
101 beanState.put(methodName.substring(SET_PREFIX.length()), args[0]);
102 return proxy;
103
104 } else {
105 throw new IllegalArgumentException(String.format("method %s.%s() is not a valid getter/setter", method
106 .getDeclaringClass().getName(), methodName));
107 }
108
109 }
110 }