Elffuss BraidHub

kikocis/java-driver public

e2b12eeb741a · 2.4 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.*;
21
22class AccessorInvocationHandler<T> implements InvocationHandler {
23
24 private static final Object[] NO_ARGS = new Object[0];
25
26 private static final Method TO_STRING;
27 private static final Method EQUALS;
28 private static final Method HASH_CODE;
29 static {
30 try {
31 TO_STRING = Object.class.getMethod("toString");
32 EQUALS = Object.class.getMethod("equals", Object.class);
33 HASH_CODE = Object.class.getMethod("hashCode");
34 } catch (NoSuchMethodException e) {
35 throw new AssertionError(e); // Can't happen
36 }
37 }
38
39 private final AccessorMapper<T> mapper;
40
41 private final Map<Method, MethodMapper> methodMap = new HashMap<Method, MethodMapper>();
42
43 AccessorInvocationHandler(AccessorMapper<T> mapper) {
44 this.mapper = mapper;
45
46 for (MethodMapper method : mapper.methods)
47 methodMap.put(method.method, method);
48 }
49
50 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
51 if (m.equals(TO_STRING))
52 return mapper.daoClass.getSimpleName() + " implementation generated by the Cassandra driver mapper";
53
54 // It's unlikely that equals and hashCode will be used on accessor implementations, but better safe than sorry.
55 // Identity equality is enough, given that the mapper always returns the same instance for a given accessor.
56 if (m.equals(EQUALS))
57 return proxy == args[0];
58
59 if (m.equals(HASH_CODE))
60 return System.identityHashCode(proxy);
61
62 MethodMapper method = methodMap.get(m);
63 if (method == null)
64 throw new UnsupportedOperationException();
65 return method.invoke(args == null ? NO_ARGS : args);
66 }
67}
68