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.checkNotNull;
018
019import com.google.common.collect.ImmutableList;
020import com.google.errorprone.annotations.CanIgnoreReturnValue;
021import java.lang.annotation.Annotation;
022import java.lang.reflect.AccessibleObject;
023import java.lang.reflect.AnnotatedElement;
024import java.lang.reflect.AnnotatedType;
025import java.lang.reflect.Constructor;
026import java.lang.reflect.InvocationTargetException;
027import java.lang.reflect.Member;
028import java.lang.reflect.Method;
029import java.lang.reflect.Modifier;
030import java.lang.reflect.Type;
031import java.lang.reflect.TypeVariable;
032import java.util.Arrays;
033import javax.annotation.CheckForNull;
034import org.checkerframework.checker.nullness.qual.Nullable;
035
036/**
037 * Wrapper around either a {@link Method} or a {@link Constructor}. Convenience API is provided to
038 * make common reflective operation easier to deal with, such as {@link #isPublic}, {@link
039 * #getParameters} etc.
040 *
041 * <p>In addition to convenience methods, {@link TypeToken#method} and {@link TypeToken#constructor}
042 * will resolve the type parameters of the method or constructor in the context of the owner type,
043 * which may be a subtype of the declaring class. For example:
044 *
045 * <pre>{@code
046 * Method getMethod = List.class.getMethod("get", int.class);
047 * Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod);
048 * assertEquals(TypeToken.of(String.class), invokable.getReturnType()); // Not Object.class!
049 * assertEquals(new TypeToken<List<String>>() {}, invokable.getOwnerType());
050 * }</pre>
051 *
052 * <p><b>Note:</b> earlier versions of this class inherited from {@link
053 * java.lang.reflect.AccessibleObject AccessibleObject} and {@link
054 * java.lang.reflect.GenericDeclaration GenericDeclaration}. Since version 31.0 that is no longer
055 * the case. However, most methods from those types are present with the same signature in this
056 * class.
057 *
058 * @param <T> the type that owns this method or constructor.
059 * @param <R> the return type of (or supertype thereof) the method or the declaring type of the
060 *     constructor.
061 * @author Ben Yu
062 * @since 14.0 (no longer implements {@link AccessibleObject} or {@code GenericDeclaration} since
063 *     31.0)
064 */
065@ElementTypesAreNonnullByDefault
066public abstract class Invokable<T, R> implements AnnotatedElement, Member {
067  private final AccessibleObject accessibleObject;
068  private final Member member;
069
070  <M extends AccessibleObject & Member> Invokable(M member) {
071    checkNotNull(member);
072    this.accessibleObject = member;
073    this.member = member;
074  }
075
076  /** Returns {@link Invokable} of {@code method}. */
077  public static Invokable<?, Object> from(Method method) {
078    return new MethodInvokable<>(method);
079  }
080
081  /** Returns {@link Invokable} of {@code constructor}. */
082  public static <T> Invokable<T, T> from(Constructor<T> constructor) {
083    return new ConstructorInvokable<T>(constructor);
084  }
085
086  @Override
087  public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
088    return accessibleObject.isAnnotationPresent(annotationClass);
089  }
090
091  @Override
092  @CheckForNull
093  public final <A extends Annotation> 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(@CheckForNull 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  @CheckForNull
258  public final R invoke(@CheckForNull T receiver, @Nullable Object... args)
259      throws InvocationTargetException, IllegalAccessException {
260    return (R) invokeInternal(receiver, checkNotNull(args));
261  }
262
263  /** Returns the return type of this {@code Invokable}. */
264  // All subclasses are owned by us and we'll make sure to get the R type right.
265  @SuppressWarnings("unchecked")
266  public final TypeToken<? extends R> getReturnType() {
267    return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType());
268  }
269
270  /**
271   * Returns all declared parameters of this {@code Invokable}. Note that if this is a constructor
272   * of a non-static inner class, unlike {@link Constructor#getParameterTypes}, the hidden {@code
273   * this} parameter of the enclosing class is excluded from the returned parameters.
274   */
275  @IgnoreJRERequirement
276  public final ImmutableList<Parameter> getParameters() {
277    Type[] parameterTypes = getGenericParameterTypes();
278    Annotation[][] annotations = getParameterAnnotations();
279    @Nullable Object[] annotatedTypes =
280        ANNOTATED_TYPE_EXISTS ? getAnnotatedParameterTypes() : new Object[parameterTypes.length];
281    ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
282    for (int i = 0; i < parameterTypes.length; i++) {
283      builder.add(
284          new Parameter(
285              this, i, TypeToken.of(parameterTypes[i]), annotations[i], annotatedTypes[i]));
286    }
287    return builder.build();
288  }
289
290  /** Returns all declared exception types of this {@code Invokable}. */
291  public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
292    ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
293    for (Type type : getGenericExceptionTypes()) {
294      // getGenericExceptionTypes() will never return a type that's not exception
295      @SuppressWarnings("unchecked")
296      TypeToken<? extends Throwable> exceptionType =
297          (TypeToken<? extends Throwable>) TypeToken.of(type);
298      builder.add(exceptionType);
299    }
300    return builder.build();
301  }
302
303  /**
304   * Explicitly specifies the return type of this {@code Invokable}. For example:
305   *
306   * <pre>{@code
307   * Method factoryMethod = Person.class.getMethod("create");
308   * Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);
309   * }</pre>
310   */
311  public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) {
312    return returning(TypeToken.of(returnType));
313  }
314
315  /** Explicitly specifies the return type of this {@code Invokable}. */
316  public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) {
317    if (!returnType.isSupertypeOf(getReturnType())) {
318      throw new IllegalArgumentException(
319          "Invokable is known to return " + getReturnType() + ", not " + returnType);
320    }
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  @CheckForNull
340  abstract Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
341      throws InvocationTargetException, IllegalAccessException;
342
343  abstract Type[] getGenericParameterTypes();
344
345  @SuppressWarnings("Java7ApiChecker")
346  abstract AnnotatedType[] getAnnotatedParameterTypes();
347
348  /** This should never return a type that's not a subtype of Throwable. */
349  abstract Type[] getGenericExceptionTypes();
350
351  abstract Annotation[][] getParameterAnnotations();
352
353  abstract Type getGenericReturnType();
354
355  /**
356   * Returns the {@link AnnotatedType} for the return type.
357   *
358   * @since 14.0
359   */
360  @SuppressWarnings("Java7ApiChecker")
361  public abstract AnnotatedType getAnnotatedReturnType();
362
363  static class MethodInvokable<T> extends Invokable<T, Object> {
364
365    final Method method;
366
367    MethodInvokable(Method method) {
368      super(method);
369      this.method = method;
370    }
371
372    @Override
373    @CheckForNull
374    final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
375        throws InvocationTargetException, IllegalAccessException {
376      return method.invoke(receiver, args);
377    }
378
379    @Override
380    Type getGenericReturnType() {
381      return method.getGenericReturnType();
382    }
383
384    @Override
385    Type[] getGenericParameterTypes() {
386      return method.getGenericParameterTypes();
387    }
388
389    @Override
390    @SuppressWarnings("Java7ApiChecker")
391    AnnotatedType[] getAnnotatedParameterTypes() {
392      return method.getAnnotatedParameterTypes();
393    }
394
395    @Override
396    @SuppressWarnings("Java7ApiChecker")
397    public AnnotatedType getAnnotatedReturnType() {
398      return method.getAnnotatedReturnType();
399    }
400
401    @Override
402    Type[] getGenericExceptionTypes() {
403      return method.getGenericExceptionTypes();
404    }
405
406    @Override
407    final Annotation[][] getParameterAnnotations() {
408      return method.getParameterAnnotations();
409    }
410
411    @Override
412    public final TypeVariable<?>[] getTypeParameters() {
413      return method.getTypeParameters();
414    }
415
416    @Override
417    public final boolean isOverridable() {
418      return !(isFinal()
419          || isPrivate()
420          || isStatic()
421          || Modifier.isFinal(getDeclaringClass().getModifiers()));
422    }
423
424    @Override
425    public final boolean isVarArgs() {
426      return method.isVarArgs();
427    }
428  }
429
430  static class ConstructorInvokable<T> extends Invokable<T, T> {
431
432    final Constructor<?> constructor;
433
434    ConstructorInvokable(Constructor<?> constructor) {
435      super(constructor);
436      this.constructor = constructor;
437    }
438
439    @Override
440    final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args)
441        throws InvocationTargetException, IllegalAccessException {
442      try {
443        return constructor.newInstance(args);
444      } catch (InstantiationException e) {
445        throw new RuntimeException(constructor + " failed.", e);
446      }
447    }
448
449    /**
450     * If the class is parameterized, such as {@link java.util.ArrayList ArrayList}, this returns
451     * {@code ArrayList<E>}.
452     */
453    @Override
454    Type getGenericReturnType() {
455      Class<?> declaringClass = getDeclaringClass();
456      TypeVariable<?>[] typeParams = declaringClass.getTypeParameters();
457      if (typeParams.length > 0) {
458        return Types.newParameterizedType(declaringClass, typeParams);
459      } else {
460        return declaringClass;
461      }
462    }
463
464    @Override
465    Type[] getGenericParameterTypes() {
466      Type[] types = constructor.getGenericParameterTypes();
467      if (types.length > 0 && mayNeedHiddenThis()) {
468        Class<?>[] rawParamTypes = constructor.getParameterTypes();
469        if (types.length == rawParamTypes.length
470            && rawParamTypes[0] == getDeclaringClass().getEnclosingClass()) {
471          // first parameter is the hidden 'this'
472          return Arrays.copyOfRange(types, 1, types.length);
473        }
474      }
475      return types;
476    }
477
478    @Override
479    @SuppressWarnings("Java7ApiChecker")
480    AnnotatedType[] getAnnotatedParameterTypes() {
481      return constructor.getAnnotatedParameterTypes();
482    }
483
484    @Override
485    @SuppressWarnings("Java7ApiChecker")
486    public AnnotatedType getAnnotatedReturnType() {
487      return constructor.getAnnotatedReturnType();
488    }
489
490    @Override
491    Type[] getGenericExceptionTypes() {
492      return constructor.getGenericExceptionTypes();
493    }
494
495    @Override
496    final Annotation[][] getParameterAnnotations() {
497      return constructor.getParameterAnnotations();
498    }
499
500    /**
501     * {@inheritDoc}
502     *
503     * <p>{@code [<E>]} will be returned for ArrayList's constructor. When both the class and the
504     * constructor have type parameters, the class parameters are prepended before those of the
505     * constructor's. This is an arbitrary rule since no existing language spec mandates one way or
506     * the other. From the declaration syntax, the class type parameter appears first, but the call
507     * syntax may show up in opposite order such as {@code new <A>Foo<B>()}.
508     */
509    @Override
510    public final TypeVariable<?>[] getTypeParameters() {
511      TypeVariable<?>[] declaredByClass = getDeclaringClass().getTypeParameters();
512      TypeVariable<?>[] declaredByConstructor = constructor.getTypeParameters();
513      TypeVariable<?>[] result =
514          new TypeVariable<?>[declaredByClass.length + declaredByConstructor.length];
515      System.arraycopy(declaredByClass, 0, result, 0, declaredByClass.length);
516      System.arraycopy(
517          declaredByConstructor, 0, result, declaredByClass.length, declaredByConstructor.length);
518      return result;
519    }
520
521    @Override
522    public final boolean isOverridable() {
523      return false;
524    }
525
526    @Override
527    public final boolean isVarArgs() {
528      return constructor.isVarArgs();
529    }
530
531    private boolean mayNeedHiddenThis() {
532      Class<?> declaringClass = constructor.getDeclaringClass();
533      if (declaringClass.getEnclosingConstructor() != null) {
534        // Enclosed in a constructor, needs hidden this
535        return true;
536      }
537      Method enclosingMethod = declaringClass.getEnclosingMethod();
538      if (enclosingMethod != null) {
539        // Enclosed in a method, if it's not static, must need hidden this.
540        return !Modifier.isStatic(enclosingMethod.getModifiers());
541      } else {
542        // Strictly, this doesn't necessarily indicate a hidden 'this' in the case of
543        // static initializer. But there seems no way to tell in that case. :(
544        // This may cause issues when an anonymous class is created inside a static initializer,
545        // and the class's constructor's first parameter happens to be the enclosing class.
546        // In such case, we may mistakenly think that the class is within a non-static context
547        // and the first parameter is the hidden 'this'.
548        return declaringClass.getEnclosingClass() != null
549            && !Modifier.isStatic(declaringClass.getModifiers());
550      }
551    }
552  }
553
554  private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists();
555
556  private static boolean initAnnotatedTypeExists() {
557    try {
558      Class.forName("java.lang.reflect.AnnotatedType");
559    } catch (ClassNotFoundException e) {
560      return false;
561    }
562    return true;
563  }
564}