001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.reflect;
016
017import com.google.common.annotations.Beta;
018import java.lang.reflect.InvocationHandler;
019import java.lang.reflect.Method;
020import java.lang.reflect.Proxy;
021import java.util.Arrays;
022import javax.annotation.Nullable;
023
024/**
025 * Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals},
026 * {@link Object#hashCode} and {@link Object#toString}. For example: <pre>
027 * class Unsupported extends AbstractInvocationHandler {
028 *   protected Object handleInvocation(Object proxy, Method method, Object[] args) {
029 *     throw new UnsupportedOperationException();
030 *   }
031 * }
032 *
033 * CharSequence unsupported = Reflection.newProxy(CharSequence.class, new Unsupported());
034 * </pre>
035 *
036 * @author Ben Yu
037 * @since 12.0
038 */
039@Beta
040public abstract class AbstractInvocationHandler implements InvocationHandler {
041
042  private static final Object[] NO_ARGS = {};
043
044  /**
045   * {@inheritDoc}
046   *
047   * <ul>
048   * <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode}
049   * <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString}
050   * <li>{@code proxy.equals(argument)} returns true if:
051   *   <ul>
052   *   <li>{@code proxy} and {@code argument} are of the same type
053   *   <li>and {@link AbstractInvocationHandler#equals} returns true for the
054   *       {@link InvocationHandler} of {@code argument}
055   *   </ul>
056   * <li>other method calls are dispatched to {@link #handleInvocation}.
057   * </ul>
058   */
059  @Override
060  public final Object invoke(Object proxy, Method method, @Nullable Object[] args)
061      throws Throwable {
062    if (args == null) {
063      args = NO_ARGS;
064    }
065    if (args.length == 0 && method.getName().equals("hashCode")) {
066      return hashCode();
067    }
068    if (args.length == 1
069        && method.getName().equals("equals")
070        && method.getParameterTypes()[0] == Object.class) {
071      Object arg = args[0];
072      if (arg == null) {
073        return false;
074      }
075      if (proxy == arg) {
076        return true;
077      }
078      return isProxyOfSameInterfaces(arg, proxy.getClass())
079          && equals(Proxy.getInvocationHandler(arg));
080    }
081    if (args.length == 0 && method.getName().equals("toString")) {
082      return toString();
083    }
084    return handleInvocation(proxy, method, args);
085  }
086
087  /**
088   * {@link #invoke} delegates to this method upon any method invocation on the proxy instance,
089   * except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result
090   * will be returned as the proxied method's return value.
091   *
092   * <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter,
093   * an empty array is passed in.
094   */
095  protected abstract Object handleInvocation(Object proxy, Method method, Object[] args)
096      throws Throwable;
097
098  /**
099   * 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}