Elffuss BraidHub

kikocis/java-driver public

3.1.x · 2.5 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import java.lang.reflect.InvocationHandler;
19import java.lang.reflect.Method;
20import java.util.HashMap;
21import java.util.Map;
22
23class AccessorInvocationHandler<T> implements InvocationHandler {
24
25 private static final Object[] NO_ARGS = new Object[0];
26
27 private static final Method TO_STRING;
28 private static final Method EQUALS;
29 private static final Method HASH_CODE;
30
31 static {
32 try {
33 TO_STRING = Object.class.getMethod("toString");
34 EQUALS = Object.class.getMethod("equals", Object.class);
35 HASH_CODE = Object.class.getMethod("hashCode");
36 } catch (NoSuchMethodException e) {
37 throw new AssertionError(e); // Can't happen
38 }
39 }
40
41 private final AccessorMapper<T> mapper;
42
43 private final Map<Method, MethodMapper> methodMap = new HashMap<Method, MethodMapper>();
44
45 AccessorInvocationHandler(AccessorMapper<T> mapper) {
46 this.mapper = mapper;
47
48 for (MethodMapper method : mapper.methods)
49 methodMap.put(method.method, method);
50 }
51
52 @Override
53 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
54 if (m.equals(TO_STRING))
55 return mapper.daoClass.getSimpleName() + " implementation generated by the Cassandra driver mapper";
56
57 // It's unlikely that equals and hashCode will be used on accessor implementations, but better safe than sorry.
58 // Identity equality is enough, given that the mapper always returns the same instance for a given accessor.
59 if (m.equals(EQUALS))
60 return proxy == args[0];
61
62 if (m.equals(HASH_CODE))
63 return System.identityHashCode(proxy);
64
65 MethodMapper method = methodMap.get(m);
66 if (method == null)
67 throw new UnsupportedOperationException();
68 return method.invoke(args == null ? NO_ARGS : args);
69 }
70}
71