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 public final boolean trySetAccessible() { 121 // We can't call accessibleObject.trySetAccessible since that was added in Java 9 and this code 122 // should work on Java 8. So we emulate it this way. 123 try { 124 accessibleObject.setAccessible(true); 125 return true; 126 } catch (RuntimeException e) { 127 return false; 128 } 129 } 130 131 /** See {@link java.lang.reflect.AccessibleObject#isAccessible()}. */ 132 public final boolean isAccessible() { 133 return accessibleObject.isAccessible(); 134 } 135 136 @Override 137 public final String getName() { 138 return member.getName(); 139 } 140 141 @Override 142 public final int getModifiers() { 143 return member.getModifiers(); 144 } 145 146 @Override 147 public final boolean isSynthetic() { 148 return member.isSynthetic(); 149 } 150 151 /** Returns true if the element is public. */ 152 public final boolean isPublic() { 153 return Modifier.isPublic(getModifiers()); 154 } 155 156 /** Returns true if the element is protected. */ 157 public final boolean isProtected() { 158 return Modifier.isProtected(getModifiers()); 159 } 160 161 /** Returns true if the element is package-private. */ 162 public final boolean isPackagePrivate() { 163 return !isPrivate() && !isPublic() && !isProtected(); 164 } 165 166 /** Returns true if the element is private. */ 167 public final boolean isPrivate() { 168 return Modifier.isPrivate(getModifiers()); 169 } 170 171 /** Returns true if the element is static. */ 172 public final boolean isStatic() { 173 return Modifier.isStatic(getModifiers()); 174 } 175 176 /** 177 * Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}. 178 * 179 * <p>Note that a method may still be effectively "final", or non-overridable when it has no 180 * {@code final} keyword. For example, it could be private, or it could be declared by a final 181 * class. To tell whether a method is overridable, use {@link Invokable#isOverridable}. 182 */ 183 public final boolean isFinal() { 184 return Modifier.isFinal(getModifiers()); 185 } 186 187 /** Returns true if the method is abstract. */ 188 public final boolean isAbstract() { 189 return Modifier.isAbstract(getModifiers()); 190 } 191 192 /** Returns true if the element is native. */ 193 public final boolean isNative() { 194 return Modifier.isNative(getModifiers()); 195 } 196 197 /** Returns true if the method is synchronized. */ 198 public final boolean isSynchronized() { 199 return Modifier.isSynchronized(getModifiers()); 200 } 201 202 /** Returns true if the field is volatile. */ 203 final boolean isVolatile() { 204 return Modifier.isVolatile(getModifiers()); 205 } 206 207 /** Returns true if the field is transient. */ 208 final boolean isTransient() { 209 return Modifier.isTransient(getModifiers()); 210 } 211 212 @Override 213 public boolean equals(@CheckForNull Object obj) { 214 if (obj instanceof Invokable) { 215 Invokable<?, ?> that = (Invokable<?, ?>) obj; 216 return getOwnerType().equals(that.getOwnerType()) && member.equals(that.member); 217 } 218 return false; 219 } 220 221 @Override 222 public int hashCode() { 223 return member.hashCode(); 224 } 225 226 @Override 227 public String toString() { 228 return member.toString(); 229 } 230 231 /** 232 * Returns {@code true} if this is an overridable method. Constructors, private, static or final 233 * methods, or methods declared by final classes are not overridable. 234 */ 235 public abstract boolean isOverridable(); 236 237 /** Returns {@code true} if this was declared to take a variable number of arguments. */ 238 public abstract boolean isVarArgs(); 239 240 /** 241 * Invokes with {@code receiver} as 'this' and {@code args} passed to the underlying method and 242 * returns the return value; or calls the underlying constructor with {@code args} and returns the 243 * constructed instance. 244 * 245 * @throws IllegalAccessException if this {@code Constructor} object enforces Java language access 246 * control and the underlying method or constructor is inaccessible. 247 * @throws IllegalArgumentException if the number of actual and formal parameters differ; if an 248 * unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a 249 * parameter value cannot be converted to the corresponding formal parameter type by a method 250 * invocation conversion. 251 * @throws InvocationTargetException if the underlying method or constructor throws an exception. 252 */ 253 // All subclasses are owned by us and we'll make sure to get the R type right, including nullness. 254 @SuppressWarnings({"unchecked", "nullness"}) 255 @CanIgnoreReturnValue 256 @CheckForNull 257 public final R invoke(@CheckForNull 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 * <pre>{@code 306 * Method factoryMethod = Person.class.getMethod("create"); 307 * Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class); 308 * }</pre> 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 if (!returnType.isSupertypeOf(getReturnType())) { 317 throw new IllegalArgumentException( 318 "Invokable is known to return " + getReturnType() + ", not " + returnType); 319 } 320 @SuppressWarnings("unchecked") // guarded by previous check 321 Invokable<T, R1> specialized = (Invokable<T, R1>) this; 322 return specialized; 323 } 324 325 @SuppressWarnings("unchecked") // The declaring class is T's raw class, or one of its supertypes. 326 @Override 327 public final Class<? super T> getDeclaringClass() { 328 return (Class<? super T>) member.getDeclaringClass(); 329 } 330 331 /** Returns the type of {@code T}. */ 332 // Overridden in TypeToken#method() and TypeToken#constructor() 333 @SuppressWarnings("unchecked") // The declaring class is T. 334 public TypeToken<T> getOwnerType() { 335 return (TypeToken<T>) TypeToken.of(getDeclaringClass()); 336 } 337 338 @CheckForNull 339 abstract Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args) 340 throws InvocationTargetException, IllegalAccessException; 341 342 abstract Type[] getGenericParameterTypes(); 343 344 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"}) 345 @IgnoreJRERequirement 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 * <p>This method will fail if run under an Android VM. 359 * 360 * @since 14.0 for guava-jre (available since 32.0.0 in guava-android) 361 */ 362 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"}) 363 @IgnoreJRERequirement 364 public abstract AnnotatedType getAnnotatedReturnType(); 365 366 static class MethodInvokable<T> extends Invokable<T, Object> { 367 368 final Method method; 369 370 MethodInvokable(Method method) { 371 super(method); 372 this.method = method; 373 } 374 375 @Override 376 @CheckForNull 377 final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args) 378 throws InvocationTargetException, IllegalAccessException { 379 return method.invoke(receiver, args); 380 } 381 382 @Override 383 Type getGenericReturnType() { 384 return method.getGenericReturnType(); 385 } 386 387 @Override 388 Type[] getGenericParameterTypes() { 389 return method.getGenericParameterTypes(); 390 } 391 392 @Override 393 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"}) 394 @IgnoreJRERequirement 395 AnnotatedType[] getAnnotatedParameterTypes() { 396 return method.getAnnotatedParameterTypes(); 397 } 398 399 @Override 400 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"}) 401 @IgnoreJRERequirement 402 public AnnotatedType getAnnotatedReturnType() { 403 return method.getAnnotatedReturnType(); 404 } 405 406 @Override 407 Type[] getGenericExceptionTypes() { 408 return method.getGenericExceptionTypes(); 409 } 410 411 @Override 412 final Annotation[][] getParameterAnnotations() { 413 return method.getParameterAnnotations(); 414 } 415 416 @Override 417 public final TypeVariable<?>[] getTypeParameters() { 418 return method.getTypeParameters(); 419 } 420 421 @Override 422 public final boolean isOverridable() { 423 return !(isFinal() 424 || isPrivate() 425 || isStatic() 426 || Modifier.isFinal(getDeclaringClass().getModifiers())); 427 } 428 429 @Override 430 public final boolean isVarArgs() { 431 return method.isVarArgs(); 432 } 433 } 434 435 static class ConstructorInvokable<T> extends Invokable<T, T> { 436 437 final Constructor<?> constructor; 438 439 ConstructorInvokable(Constructor<?> constructor) { 440 super(constructor); 441 this.constructor = constructor; 442 } 443 444 @Override 445 final Object invokeInternal(@CheckForNull Object receiver, @Nullable Object[] args) 446 throws InvocationTargetException, IllegalAccessException { 447 try { 448 return constructor.newInstance(args); 449 } catch (InstantiationException e) { 450 throw new RuntimeException(constructor + " failed.", e); 451 } 452 } 453 454 /** 455 * If the class is parameterized, such as {@link java.util.ArrayList ArrayList}, this returns 456 * {@code ArrayList<E>}. 457 */ 458 @Override 459 Type getGenericReturnType() { 460 Class<?> declaringClass = getDeclaringClass(); 461 TypeVariable<?>[] typeParams = declaringClass.getTypeParameters(); 462 if (typeParams.length > 0) { 463 return Types.newParameterizedType(declaringClass, typeParams); 464 } else { 465 return declaringClass; 466 } 467 } 468 469 @Override 470 Type[] getGenericParameterTypes() { 471 Type[] types = constructor.getGenericParameterTypes(); 472 if (types.length > 0 && mayNeedHiddenThis()) { 473 Class<?>[] rawParamTypes = constructor.getParameterTypes(); 474 if (types.length == rawParamTypes.length 475 && rawParamTypes[0] == getDeclaringClass().getEnclosingClass()) { 476 // first parameter is the hidden 'this' 477 return Arrays.copyOfRange(types, 1, types.length); 478 } 479 } 480 return types; 481 } 482 483 @Override 484 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker"}) 485 @IgnoreJRERequirement 486 AnnotatedType[] getAnnotatedParameterTypes() { 487 return constructor.getAnnotatedParameterTypes(); 488 } 489 490 @Override 491 @SuppressWarnings({"Java7ApiChecker", "AndroidJdkLibsChecker", "DoNotCall"}) 492 @IgnoreJRERequirement 493 public AnnotatedType getAnnotatedReturnType() { 494 return constructor.getAnnotatedReturnType(); 495 } 496 497 @Override 498 Type[] getGenericExceptionTypes() { 499 return constructor.getGenericExceptionTypes(); 500 } 501 502 @Override 503 final Annotation[][] getParameterAnnotations() { 504 return constructor.getParameterAnnotations(); 505 } 506 507 /** 508 * {@inheritDoc} 509 * 510 * <p>{@code [<E>]} will be returned for ArrayList's constructor. When both the class and the 511 * constructor have type parameters, the class parameters are prepended before those of the 512 * constructor's. This is an arbitrary rule since no existing language spec mandates one way or 513 * the other. From the declaration syntax, the class type parameter appears first, but the call 514 * syntax may show up in opposite order such as {@code new <A>Foo<B>()}. 515 */ 516 @Override 517 public final TypeVariable<?>[] getTypeParameters() { 518 TypeVariable<?>[] declaredByClass = getDeclaringClass().getTypeParameters(); 519 TypeVariable<?>[] declaredByConstructor = constructor.getTypeParameters(); 520 TypeVariable<?>[] result = 521 new TypeVariable<?>[declaredByClass.length + declaredByConstructor.length]; 522 System.arraycopy(declaredByClass, 0, result, 0, declaredByClass.length); 523 System.arraycopy( 524 declaredByConstructor, 0, result, declaredByClass.length, declaredByConstructor.length); 525 return result; 526 } 527 528 @Override 529 public final boolean isOverridable() { 530 return false; 531 } 532 533 @Override 534 public final boolean isVarArgs() { 535 return constructor.isVarArgs(); 536 } 537 538 private boolean mayNeedHiddenThis() { 539 Class<?> declaringClass = constructor.getDeclaringClass(); 540 if (declaringClass.getEnclosingConstructor() != null) { 541 // Enclosed in a constructor, needs hidden this 542 return true; 543 } 544 Method enclosingMethod = declaringClass.getEnclosingMethod(); 545 if (enclosingMethod != null) { 546 // Enclosed in a method, if it's not static, must need hidden this. 547 return !Modifier.isStatic(enclosingMethod.getModifiers()); 548 } else { 549 // Strictly, this doesn't necessarily indicate a hidden 'this' in the case of 550 // static initializer. But there seems no way to tell in that case. :( 551 // This may cause issues when an anonymous class is created inside a static initializer, 552 // and the class's constructor's first parameter happens to be the enclosing class. 553 // In such case, we may mistakenly think that the class is within a non-static context 554 // and the first parameter is the hidden 'this'. 555 return declaringClass.getEnclosingClass() != null 556 && !Modifier.isStatic(declaringClass.getModifiers()); 557 } 558 } 559 } 560 561 private static final boolean ANNOTATED_TYPE_EXISTS = initAnnotatedTypeExists(); 562 563 private static boolean initAnnotatedTypeExists() { 564 try { 565 Class.forName("java.lang.reflect.AnnotatedType"); 566 } catch (ClassNotFoundException e) { 567 return false; 568 } 569 return true; 570 } 571}