View Javadoc
1   /*
2    * Copyright (C) 2012 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.reflect;
16  
17  import com.google.common.annotations.Beta;
18  import java.lang.reflect.InvocationHandler;
19  import java.lang.reflect.Method;
20  import java.lang.reflect.Proxy;
21  import java.util.Arrays;
22  import javax.annotation.Nullable;
23  
24  /**
25   * Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals},
26   * {@link Object#hashCode} and {@link Object#toString}. For example: <pre>
27   * class Unsupported extends AbstractInvocationHandler {
28   *   protected Object handleInvocation(Object proxy, Method method, Object[] args) {
29   *     throw new UnsupportedOperationException();
30   *   }
31   * }
32   *
33   * CharSequence unsupported = Reflection.newProxy(CharSequence.class, new Unsupported());
34   * </pre>
35   *
36   * @author Ben Yu
37   * @since 12.0
38   */
39  @Beta
40  public abstract class AbstractInvocationHandler implements InvocationHandler {
41  
42    private static final Object[] NO_ARGS = {};
43  
44    /**
45     * {@inheritDoc}
46     *
47     * <ul>
48     * <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode}
49     * <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString}
50     * <li>{@code proxy.equals(argument)} returns true if:
51     *   <ul>
52     *   <li>{@code proxy} and {@code argument} are of the same type
53     *   <li>and {@link AbstractInvocationHandler#equals} returns true for the
54     *       {@link InvocationHandler} of {@code argument}
55     *   </ul>
56     * <li>other method calls are dispatched to {@link #handleInvocation}.
57     * </ul>
58     */
59    @Override
60    public final Object invoke(Object proxy, Method method, @Nullable Object[] args)
61        throws Throwable {
62      if (args == null) {
63        args = NO_ARGS;
64      }
65      if (args.length == 0 && method.getName().equals("hashCode")) {
66        return hashCode();
67      }
68      if (args.length == 1
69          && method.getName().equals("equals")
70          && method.getParameterTypes()[0] == Object.class) {
71        Object arg = args[0];
72        if (arg == null) {
73          return false;
74        }
75        if (proxy == arg) {
76          return true;
77        }
78        return isProxyOfSameInterfaces(arg, proxy.getClass())
79            && equals(Proxy.getInvocationHandler(arg));
80      }
81      if (args.length == 0 && method.getName().equals("toString")) {
82        return toString();
83      }
84      return handleInvocation(proxy, method, args);
85    }
86  
87    /**
88     * {@link #invoke} delegates to this method upon any method invocation on the proxy instance,
89     * except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result
90     * will be returned as the proxied method's return value.
91     *
92     * <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter,
93     * an empty array is passed in.
94     */
95    protected abstract Object handleInvocation(Object proxy, Method method, Object[] args)
96        throws Throwable;
97  
98    /**
99     * By default delegates to {@link Object#equals} so instances are only equal if they are
100    * identical. {@code proxy.equals(argument)} returns true if:
101    *
102    * <ul>
103    * <li>{@code proxy} and {@code argument} are of the same type
104    * <li>and this method returns true for the {@link InvocationHandler} of {@code argument}
105    * </ul>
106    *
107    * <p>Subclasses can override this method to provide custom equality.
108    */
109   @Override
110   public boolean equals(Object obj) {
111     return super.equals(obj);
112   }
113 
114   /**
115    * By default delegates to {@link Object#hashCode}. The dynamic proxies' {@code hashCode()} will
116    * delegate to this method. Subclasses can override this method to provide custom equality.
117    */
118   @Override
119   public int hashCode() {
120     return super.hashCode();
121   }
122 
123   /**
124    * By default delegates to {@link Object#toString}. The dynamic proxies' {@code toString()} will
125    * delegate to this method. Subclasses can override this method to provide custom string
126    * representation for the proxies.
127    */
128   @Override
129   public String toString() {
130     return super.toString();
131   }
132 
133   private static boolean isProxyOfSameInterfaces(Object arg, Class<?> proxyClass) {
134     return proxyClass.isInstance(arg)
135         // Equal proxy instances should mostly be instance of proxyClass
136         // Under some edge cases (such as the proxy of JDK types serialized and then deserialized)
137         // the proxy type may not be the same.
138         // We first check isProxyClass() so that the common case of comparing with non-proxy objects
139         // is efficient.
140         || (Proxy.isProxyClass(arg.getClass())
141             && Arrays.equals(arg.getClass().getInterfaces(), proxyClass.getInterfaces()));
142   }
143 }