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 static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.reflect.Types.newParameterizedType;
020import static java.lang.System.arraycopy;
021
022import com.google.common.collect.ImmutableList;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import java.lang.annotation.Annotation;
025import java.lang.reflect.AccessibleObject;
026import java.lang.reflect.AnnotatedElement;
027import java.lang.reflect.AnnotatedType;
028import java.lang.reflect.Constructor;
029import java.lang.reflect.InvocationTargetException;
030import java.lang.reflect.Member;
031import java.lang.reflect.Method;
032import java.lang.reflect.Modifier;
033import java.lang.reflect.Type;
034import java.lang.reflect.TypeVariable;
035import java.util.Arrays;
036import org.jspecify.annotations.Nullable;
037
038/**
039 * Wrapper around either a {@link Method} or a {@link Constructor}. Convenience API is provided to
040 * make common reflective operation easier to deal with, such as {@link #isPublic}, {@link
041 * #getParameters} etc.
042 *
043 * <p>In addition to convenience methods, {@link TypeToken#method} and {@link TypeToken#constructor}
044 * will resolve the type parameters of the method or constructor in the context of the owner type,
045 * which may be a subtype of the declaring class. For example:
046 *
047 * {@snippet :
048 * Method getMethod = List.class.getMethod("get", int.class);
049 * Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
050 * assertEquals(TypeToken.of(String.class), invokable.getReturnType()); // Not Object.class!
051 * assertEquals(new TypeToken<List<String>>() {}, invokable.getOwnerType());
052 * }
053 *
054 * <p><b>Note:</b> earlier versions of this class inherited from {@link
055 * java.lang.reflect.AccessibleObject AccessibleObject} and {@link
056 * java.lang.reflect.GenericDeclaration GenericDeclaration}. Since version 31.0 that is no longer
057 * the case. However, most methods from those types are present with the same signature in this
058 * class.
059 *
060 * @param <T> the type that owns this method or constructor.
061 * @param <R> the return type of (or supertype thereof) the method or the declaring type of the
062 *     constructor.
063 * @author Ben Yu
064 * @since 14.0 (no longer implements {@link AccessibleObject} or {@code GenericDeclaration} since
065 *     31.0)
066 */
067public abstract class Invokable<T, R> implements AnnotatedElement, Member {
068  private final AccessibleObject accessibleObject;
069  private final Member member;
070
071  <M extends AccessibleObject & Member> Invokable(M member) {
072    checkNotNull(member);
073    this.accessibleObject = member;
074    this.member = member;
075  }
076
077  /** Returns {@link Invokable} of {@code method}. */
078  public static Invokable<?, Object> from(Method method) {
079    return new MethodInvokable<>(method);
080  }
081
082  /** Returns {@link Invokable} of {@code constructor}. */
083  public static <T> Invokable<T, T> from(Constructor<T> constructor) {
084    return new ConstructorInvokable<T>(constructor);
085  }
086
087  @Override
088  public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
089    return accessibleObject.isAnnotationPresent(annotationClass);
090  }
091
092  @Override
093  public final <A extends Annotation> @Nullable A getAnnotation(Class<A> annotationClass) {
094    return accessibleObject.getAnnotation(annotationClass);
095  }
096
097  @Override
098  public final Annotation[] getAnnotations() {
099    return accessibleObject.getAnnotations();
100  }
101
102  @Override
103  public final Annotation[] getDeclaredAnnotations() {
104    return accessibleObject.getDeclaredAnnotations();
105  }
106
107  // We ought to be able to implement GenericDeclaration instead its parent AnnotatedElement.
108  // That would give us this method declaration. But for some reason, implementing
109  // GenericDeclaration leads to weird errors in Android tests:
110  // IncompatibleClassChangeError: interface not implemented
111  /** See {@link java.lang.reflect.GenericDeclaration#getTypeParameters()}. */
112  public abstract TypeVariable<?>[] getTypeParameters();
113
114  /** See {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)}. */
115  public final void setAccessible(boolean flag) {
116    accessibleObject.setAccessible(flag);
117  }
118
119  /** See {@link java.lang.reflect.AccessibleObject#trySetAccessible()}. */
120  @SuppressWarnings("CatchingUnchecked") // sneaky checked exception
121  public final boolean trySetAccessible() {
122    // We can't call accessibleObject.trySetAccessible since that was added in Java 9 and this code
123    // should work on Java 8. So we emulate it this way.
124    try {
125      accessibleObject.setAccessible(true);
126      return true;
127    } catch (Exception e) { // sneaky checked exception
128      return false;
129    }
130  }
131
132  /** See {@link java.lang.reflect.AccessibleObject#isAccessible()}. */
133  public final boolean isAccessible() {
134    return accessibleObject.isAccessible();
135  }
136
137  @Override
138  public final String getName() {
139    return member.getName();
140  }
141
142  @Override
143  public final int getModifiers() {
144    return member.getModifiers();
145  }
146
147  @Override
148  public final boolean isSynthetic() {
149    return member.isSynthetic();
150  }
151
152  /** Returns true if the element is public. */
153  public final boolean isPublic() {
154    return Modifier.isPublic(getModifiers());
155  }
156
157  /** Returns true if the element is protected. */
158  public final boolean isProtected() {
159    return Modifier.isProtected(getModifiers());
160  }
161
162  /** Returns true if the element is package-private. */
163  public final boolean isPackagePrivate() {
164    return !isPrivate() && !isPublic() && !isProtected();
165  }
166
167  /** Returns true if the element is private. */
168  public final boolean isPrivate() {
169    return Modifier.isPrivate(getModifiers());
170  }
171
172  /** Returns true if the element is static. */
173  public final boolean isStatic() {
174    return Modifier.isStatic(getModifiers());
175  }
176
177  /**
178   * Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}.
179   *
180   * <p>Note that a method may still be effectively "final", or non-overridable when it has no
181   * {@code final} keyword. For example, it could be private, or it could be declared by a final
182   * class. To tell whether a method is overridable, use {@link Invokable#isOverridable}.
183   */
184  public final boolean isFinal() {
185    return Modifier.isFinal(getModifiers());
186  }
187
188  /** Returns true if the method is abstract. */
189  public final boolean isAbstract() {
190    return Modifier.isAbstract(getModifiers());
191  }
192
193  /** Returns true if the element is native. */
194  public final boolean isNative() {
195    return Modifier.isNative(getModifiers());
196  }
197
198  /** Returns true if the method is synchronized. */
199  public final boolean isSynchronized() {
200    return Modifier.isSynchronized(getModifiers());
201  }
202
203  /** Returns true if the field is volatile. */
204  final boolean isVolatile() {
205    return Modifier.isVolatile(getModifiers());
206  }
207
208  /** Returns true if the field is transient. */
209  final boolean isTransient() {
210    return Modifier.isTransient(getModifiers());
211  }
212
213  @Override
214  public boolean equals(@Nullable Object obj) {
215    if (obj instanceof Invokable) {
216      Invokable<?, ?> that = (Invokable<?, ?>) obj;
217      return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member);
218    }
219    return false;
220  }
221
222  @Override
223  public int hashCode() {
224    return member.hashCode();
225  }
226
227  @Override
228  public String toString() {
229    return member.toString();
230  }
231
232  /**
233   * Returns {@code true} if this is an overridable method. Constructors, private, static or final
234   * methods, or methods declared by final classes are not overridable.
235   */
236  public abstract boolean isOverridable();
237
238  /** Returns {@code true} if this was declared to take a variable number of arguments. */
239  public abstract boolean isVarArgs();
240
241  /**
242   * Invokes with {@code receiver} as 'this' and {@code args} passed to the underlying method and
243   * returns the return value; or calls the underlying constructor with {@code args} and returns the
244   * constructed instance.
245   *
246   * @throws IllegalAccessException if this {@code Constructor} object enforces Java language access
247   *     control and the underlying method or constructor is inaccessible.
248   * @throws IllegalArgumentException if the number of actual and formal parameters differ; if an
249   *     unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a
250   *     parameter value cannot be converted to the corresponding formal parameter type by a method
251   *     invocation conversion.
252   * @throws InvocationTargetException if the underlying method or constructor throws an exception.
253   */
254  // All subclasses are owned by us and we'll make sure to get the R type right, including nullness.
255  @SuppressWarnings({"unchecked", "nullness"})
256  @CanIgnoreReturnValue
257  public final @Nullable R invoke(@Nullable T receiver, @Nullable Object... args)
258      throws InvocationTargetException, IllegalAccessException {
259    return (R) invokeInternal(receiver, checkNotNull(args));
260  }
261
262  /** Returns the return type of this {@code Invokable}. */
263  // All subclasses are owned by us and we'll make sure to get the R type right.
264  @SuppressWarnings("unchecked")
265  public final TypeToken<? extends R> getReturnType() {
266    return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType());
267  }
268
269  /**
270   * Returns all declared parameters of this {@code Invokable}. Note that if this is a constructor
271   * of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
272   * this} parameter of the enclosing class is excluded from the returned parameters.
273   */
274  @IgnoreJRERequirement
275  public final ImmutableList<Parameter> getParameters() {
276    Type[] parameterTypes = getGenericParameterTypes();
277    Annotation[][] annotations = getParameterAnnotations();
278    @Nullable Object[] annotatedTypes =
279        ANNOTATED_TYPE_EXISTS ? getAnnotatedParameterTypes() : new Object[parameterTypes.length];
280    ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
281    for (int i = 0; i < parameterTypes.length; i++) {
282      builder.add(
283          new Parameter(
284              this, i, TypeToken.of(parameterTypes[i]), annotations[i], annotatedTypes[i]));
285    }
286    return builder.build();
287  }
288
289  /** Returns all declared exception types of this {@code Invokable}. */
290  public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
291    ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
292    for (Type type : getGenericExceptionTypes()) {
293      // getGenericExceptionTypes() will never return a type that's not exception
294      @SuppressWarnings("unchecked")
295      TypeToken<? extends Throwable> exceptionType =
296          (TypeToken<? extends Throwable>) TypeToken.of(type);
297      builder.add(exceptionType);
298    }
299    return builder.build();
300  }
301
302  /**
303   * Explicitly specifies the return type of this {@code Invokable}. For example:
304   *
305   * {@snippet :
306   * Method factoryMethod = Person.class.getMethod("create");
307   * Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);
308   * }
309   */
310  public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) {
311    return returning(TypeToken.of(returnType));
312  }
313
314  /** Explicitly specifies the return type of this {@code Invokable}. */
315  public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) {
316    checkArgument(
317        returnType.isSupertypeOf(getReturnType()),
318        "Invokable is known to return %s, not %s",
319        getReturnType(),
320        returnType);
321    @SuppressWarnings("unchecked") // guarded by previous check
322    Invokable<T, R1> specialized = (Invokable<T, R1>) this;
323    return specialized;
324  }
325
326  @SuppressWarnings("unchecked") // The declaring class is T's raw class, or one of its supertypes.
327  @Override
328  public final Class<? super T> getDeclaringClass() {
329    return (Class<? super T>) member.getDeclaringClass();
330  }
331
332  /** Returns the type of {@code T}. */
333  // Overridden in TypeToken#method() and TypeToken#constructor()
334  @SuppressWarnings("unchecked") // The declaring class is T.
335  public TypeToken<T> getOwnerType() {
336    return (TypeToken<T>) TypeToken.of(getDeclaringClass());
337  }
338
339  abstract @Nullable Object invokeInternal(@Nullable Object receiver, @Nullable Object[] args)
340      throws InvocationTargetException, IllegalAccessException;
341
342  abstract Type[] getGenericParameterTypes();
343
344  abstract AnnotatedType[] getAnnotatedParameterTypes();
345
346  /** This should never return a type that's not a subtype of Throwable. */
347  abstract Type[] getGenericExceptionTypes();
348
349  abstract Annotation[][] getParameterAnnotations();
350
351  abstract Type getGenericReturnType();
352
353  /**
354   * Returns the {@link AnnotatedType} for the return type.
355   *
356   * @since 14.0
357   */
358  public abstract AnnotatedType getAnnotatedReturnType();
359
360  static class MethodInvokable<T> extends Invokable<T, Object> {
361
362    final Method method;
363
364    MethodInvokable(Method method) {
365      super(method);
366      this.method = method;
367    }
368
369    @Override
370    final @Nullable Object invokeInternal(@Nullable Object receiver, @Nullable Object[] args)
371        throws InvocationTargetException, IllegalAccessException {
372      return method.invoke(receiver, args);
373    }
374
375    @Override
376    Type getGenericReturnType() {
377      return method.getGenericReturnType();
378    }
379
380    @Override
381    Type[] getGenericParameterTypes() {
382      return method.getGenericParameterTypes();
383    }
384
385    @Override
386    AnnotatedType[] getAnnotatedParameterTypes() {
387      return method.getAnnotatedParameterTypes();
388    }
389
390    @Override
391    public AnnotatedType getAnnotatedReturnType() {
392      return method.getAnnotatedReturnType();
393    }
394
395    @Override
396    Type[] getGenericExceptionTypes() {
397      return method.getGenericExceptionTypes();
398    }
399
400    @Override
401    final Annotation[][] getParameterAnnotations() {
402      return method.getParameterAnnotations();
403    }
404
405    @Override
406    public final TypeVariable<?>[] getTypeParameters() {
407      return method.getTypeParameters();
408    }
409
410    @Override
411    public final boolean isOverridable() {
412      return !(isFinal()
413          || isPrivate()
414          || isStatic()
415          || Modifier.isFinal(getDeclaringClass().getModifiers()));
416    }
417
418    @Override
419    public final boolean isVarArgs() {
420      return method.isVarArgs();
421    }
422  }
423
424  static class ConstructorInvokable<T> extends Invokable<T, T> {
425
426    final Constructor<?> constructor;
427
428    ConstructorInvokable(Constructor<?> constructor) {
429      super(constructor);
430      this.constructor = constructor;
431    }
432
433    @Override
434    final Object invokeInternal(@Nullable Object receiver, @Nullable Object[] args)
435        throws InvocationTargetException, IllegalAccessException {
436      try {
437        return constructor.newInstance(args);
438      } catch (InstantiationException e) {
439        throw new RuntimeException(constructor + " failed.", e);
440      }
441    }
442
443    /**
444     * If the class is parameterized, such as {@link java.util.ArrayList ArrayList}, this returns
445     * {@code ArrayList<E>}.
446     */
447    @Override
448    Type getGenericReturnType() {
449      Class<?> declaringClass = getDeclaringClass();
450      TypeVariable<?>[] typeParams = declaringClass.getTypeParameters();
451      if (typeParams.length > 0) {
452        return newParameterizedType(declaringClass, typeParams);
453      } else {
454        return declaringClass;
455      }
456    }
457
458    @Override
459    Type[] getGenericParameterTypes() {
460      Type[] types = constructor.getGenericParameterTypes();
461      if (types.length > 0 && mayNeedHiddenThis()) {
462        Class<?>[] rawParamTypes = constructor.getParameterTypes();
463        if (types.length == rawParamTypes.length
464            && rawParamTypes[0] == getDeclaringClass().getEnclosingClass()) {
465          // first parameter is the hidden 'this'
466          return Arrays.copyOfRange(types, 1, types.length);
467        }
468      }
469      return types;
470    }
471
472    @Override
473    AnnotatedType[] getAnnotatedParameterTypes() {
474      return constructor.getAnnotatedParameterTypes();
475    }
476
477    @Override
478    public AnnotatedType getAnnotatedReturnType() {
479      return constructor.getAnnotatedReturnType();
480    }
481
482    @Override
483    Type[] getGenericExceptionTypes() {
484      return constructor.getGenericExceptionTypes();
485    }
486
487    @Override
488    final Annotation[][] getParameterAnnotations() {
489      return constructor.getParameterAnnotations();
490    }
491
492    /**
493     * {@inheritDoc}
494     *
495     * <p>{@code [<E>]} will be returned for ArrayList's constructor. When both the class and the
496     * constructor have type parameters, the class parameters are prepended before those of the
497     * constructor's. This is an arbitrary rule since no existing language spec mandates one way or
498     * the other. From the declaration syntax, the class type parameter appears first, but the call
499     * syntax may show up in opposite order such as {@code new <A>Foo<B>()}.
500     */
501    @Override
502    public final TypeVariable<?>[] getTypeParameters() {
503      TypeVariable<?>[] declaredByClass = getDeclaringClass().getTypeParameters();
504      TypeVariable<?>[] declaredByConstructor = constructor.getTypeParameters();
505      TypeVariable<?>[] result =
506          new TypeVariable<?>[declaredByClass.length + declaredByConstructor.length];
507      arraycopy(declaredByClass, 0, result, 0, declaredByClass.length);
508      arraycopy(
509          declaredByConstructor, 0, result, declaredByClass.length, declaredByConstructor.length);
510      return result;
511    }
512
513    @Override
514    public final boolean isOverridable() {
515      return false;
516    }
517
518    @Override
519    public final boolean isVarArgs() {
520      return constructor.isVarArgs();
521    }
522
523    private boolean mayNeedHiddenThis() {
524      Class<?> declaringClass = constructor.getDeclaringClass();
525      if (declaringClass.getEnclosingConstructor() != null) {
526        // Enclosed in a constructor, needs hidden this
527        return true;
528      }
529      Method enclosingMethod = declaringClass.getEnclosingMethod();
530      if (enclosingMethod != null) {
531        // Enclosed in a method, if it's not static, must need hidden this.
532        return !Modifier.isStatic(enclosingMethod.getModifiers());
533      } else {
534        // Strictly, this doesn't necessarily indicate a hidden 'this' in the case of
535        // static initializer. But there seems no way to tell in that case. :(
536        // This may cause issues when an anonymous class is created inside a static initializer,
537        // and the class's constructor's first parameter happens to be the enclosing class.
538        // In such case, we may mistakenly think that the class is within a non-static context
539        // and the first parameter is the hidden 'this'.
540        return declaringClass.getEnclosingClass() != null
541            && !Modifier.isStatic(declaringClass.getModifiers());
542      }
543    }
544  }
545
546  private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists();
547
548  private static boolean initAnnotatedTypeExists() {
549    try {
550      Class.forName("java.lang.reflect.AnnotatedType");
551    } catch (ClassNotFoundException e) {
552      return false;
553    }
554    return true;
555  }
556}