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 java.lang.reflect.InvocationHandler;
018import java.lang.reflect.Method;
019import java.lang.reflect.Proxy;
020import java.util.Arrays;
021import org.jspecify.annotations.Nullable;
022
023/**
024 * Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals}, {@link
025 * Object#hashCode} and {@link Object#toString}. For example:
026 *
027 * <pre>
028 * class Unsupported extends AbstractInvocationHandler {
029 *   protected Object handleInvocation(Object proxy, Method method, Object[] args) {
030 *     throw new UnsupportedOperationException();
031 *   }
032 * }
033 *
034 * CharSequence unsupported = Reflection.newProxy(CharSequence.class, new Unsupported());
035 * </pre>
036 *
037 * @author Ben Yu
038 * @since 12.0
039 */
040public abstract class AbstractInvocationHandler implements InvocationHandler {
041  /** Constructor for use by subclasses. */
042  protected AbstractInvocationHandler() {}
043
044  private static final Object[] NO_ARGS = {};
045
046  /**
047   * {@inheritDoc}
048   *
049   * <ul>
050   *   <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode}
051   *   <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString}
052   *   <li>{@code proxy.equals(argument)} returns true if:
053   *       <ul>
054   *         <li>{@code proxy} and {@code argument} are of the same type
055   *         <li>and {@link AbstractInvocationHandler#equals} returns true for the {@link
056   *             InvocationHandler} of {@code argument}
057   *       </ul>
058   *   <li>other method calls are dispatched to {@link #handleInvocation}.
059   * </ul>
060   */
061  @SuppressWarnings("ReferenceEquality") // == fast path
062  @Override
063  public final @Nullable Object invoke(
064      Object proxy, Method method, @Nullable Object @Nullable [] args) throws Throwable {
065    if (args == null) {
066      args = NO_ARGS;
067    }
068    if (args.length == 0 && method.getName().equals("hashCode")) {
069      return hashCode();
070    }
071    if (args.length == 1
072        && method.getName().equals("equals")
073        && method.getParameterTypes()[0] == Object.class) {
074      Object arg = args[0];
075      if (arg == null) {
076        return false;
077      }
078      if (proxy == arg) {
079        return true;
080      }
081      return isProxyOfSameInterfaces(arg, proxy.getClass())
082          && equals(Proxy.getInvocationHandler(arg));
083    }
084    if (args.length == 0 && method.getName().equals("toString")) {
085      return toString();
086    }
087    return handleInvocation(proxy, method, args);
088  }
089
090  /**
091   * {@link #invoke} delegates to this method upon any method invocation on the proxy instance,
092   * except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result
093   * will be returned as the proxied method's return value.
094   *
095   * <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter,
096   * an empty array is passed in.
097   */
098  protected abstract @Nullable Object handleInvocation(
099      Object proxy, Method method, @Nullable Object[] args) throws Throwable;
100
101  /**
102   * By default delegates to {@link Object#equals} so instances are only equal if they are
103   * identical. {@code proxy.equals(argument)} returns true if:
104   *
105   * <ul>
106   *   <li>{@code proxy} and {@code argument} are of the same type
107   *   <li>and this method returns true for the {@link InvocationHandler} of {@code argument}
108   * </ul>
109   *
110   * <p>Subclasses can override this method to provide custom equality.
111   */
112  @Override
113  public boolean equals(@Nullable Object obj) {
114    return super.equals(obj);
115  }
116
117  /**
118   * By default delegates to {@link Object#hashCode}. The dynamic proxies' {@code hashCode()} will
119   * delegate to this method. Subclasses can override this method to provide custom equality.
120   */
121  @Override
122  public int hashCode() {
123    return super.hashCode();
124  }
125
126  /**
127   * By default delegates to {@link Object#toString}. The dynamic proxies' {@code toString()} will
128   * delegate to this method. Subclasses can override this method to provide custom string
129   * representation for the proxies.
130   */
131  @Override
132  public String toString() {
133    return super.toString();
134  }
135
136  private static boolean isProxyOfSameInterfaces(Object arg, Class<?> proxyClass) {
137    return proxyClass.isInstance(arg)
138        // Equal proxy instances should mostly be instance of proxyClass
139        // Under some edge cases (such as the proxy of JDK types serialized and then deserialized)
140        // the proxy type may not be the same.
141        // We first check isProxyClass() so that the common case of comparing with non-proxy objects
142        // is efficient.
143        || (Proxy.isProxyClass(arg.getClass())
144            && Arrays.equals(arg.getClass().getInterfaces(), proxyClass.getInterfaces()));
145  }
146}