001/* 002 * Copyright (C) 2009 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.base.Preconditions.checkState; 020import static com.google.common.reflect.Types.getComponentType; 021import static com.google.common.reflect.Types.newArrayType; 022import static com.google.common.reflect.Types.newArtificialTypeVariable; 023import static com.google.common.reflect.Types.newParameterizedTypeWithOwner; 024import static java.util.Arrays.asList; 025 026import com.google.common.base.Joiner; 027import com.google.common.collect.ImmutableMap; 028import com.google.errorprone.annotations.CanIgnoreReturnValue; 029import java.lang.reflect.GenericArrayType; 030import java.lang.reflect.ParameterizedType; 031import java.lang.reflect.Type; 032import java.lang.reflect.TypeVariable; 033import java.lang.reflect.WildcardType; 034import java.util.Arrays; 035import java.util.HashMap; 036import java.util.LinkedHashSet; 037import java.util.Map; 038import java.util.Map.Entry; 039import java.util.Objects; 040import java.util.Set; 041import java.util.concurrent.atomic.AtomicInteger; 042import org.jspecify.annotations.Nullable; 043 044/** 045 * An object of this class encapsulates type mappings from type variables. Mappings are established 046 * with {@link #where} and types are resolved using {@link #resolveType}. 047 * 048 * <p>Note that usually type mappings are already implied by the static type hierarchy (for example, 049 * the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in 050 * the context of {@code class MyStringList implements List<String>}). In such case, prefer to use 051 * {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be 052 * used when the type mapping isn't implied by the static type hierarchy, but provided through other 053 * means such as an annotation or external configuration file. 054 * 055 * @author Ben Yu 056 * @since 15.0 057 */ 058public final class TypeResolver { 059 060 private final TypeTable typeTable; 061 062 /** Constructs a new {@code TypeResolver} with no type mappings. */ 063 public TypeResolver() { 064 this.typeTable = new TypeTable(); 065 } 066 067 private TypeResolver(TypeTable typeTable) { 068 this.typeTable = typeTable; 069 } 070 071 /** 072 * Returns a resolver that resolves types "covariantly". 073 * 074 * <p>For example, when resolving {@code List<T>} in the context of {@code ArrayList<?>}, {@code 075 * <T>} is covariantly resolved to {@code <?>} such that return type of {@code List::get} is 076 * {@code <?>}. 077 */ 078 static TypeResolver covariantly(Type contextType) { 079 return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(contextType)); 080 } 081 082 /** 083 * Returns a resolver that resolves types "invariantly". 084 * 085 * <p>For example, when resolving {@code List<T>} in the context of {@code ArrayList<?>}, {@code 086 * <T>} cannot be invariantly resolved to {@code <?>} because otherwise the parameter type of 087 * {@code List::set} will be {@code <?>} and it'll falsely say any object can be passed into 088 * {@code ArrayList<?>::set}. 089 * 090 * <p>Instead, {@code <?>} will be resolved to a capture in the form of a type variable {@code 091 * <capture-of-? extends Object>}, effectively preventing {@code set} from accepting any type. 092 */ 093 static TypeResolver invariantly(Type contextType) { 094 Type invariantContext = WildcardCapturer.INSTANCE.capture(contextType); 095 return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(invariantContext)); 096 } 097 098 /** 099 * Returns a new {@code TypeResolver} with type variables in {@code formal} mapping to types in 100 * {@code actual}. 101 * 102 * <p>For example, if {@code formal} is a {@code TypeVariable T}, and {@code actual} is {@code 103 * String.class}, then {@code new TypeResolver().where(formal, actual)} will {@linkplain 104 * #resolveType resolve} {@code ParameterizedType List<T>} to {@code List<String>}, and resolve 105 * {@code Map<T, Something>} to {@code Map<String, Something>} etc. Similarly, {@code formal} and 106 * {@code actual} can be {@code Map<K, V>} and {@code Map<String, Integer>} respectively, or they 107 * can be {@code E[]} and {@code String[]} respectively, or even any arbitrary combination 108 * thereof. 109 * 110 * @param formal The type whose type variables or itself is mapped to other type(s). It's almost 111 * always a bug if {@code formal} isn't a type variable and contains no type variable. Make 112 * sure you are passing the two parameters in the right order. 113 * @param actual The type that the formal type variable(s) are mapped to. It can be or contain yet 114 * other type variables, in which case these type variables will be further resolved if 115 * corresponding mappings exist in the current {@code TypeResolver} instance. 116 */ 117 public TypeResolver where(Type formal, Type actual) { 118 Map<TypeVariableKey, Type> mappings = new HashMap<>(); 119 populateTypeMappings(mappings, checkNotNull(formal), checkNotNull(actual)); 120 return where(mappings); 121 } 122 123 /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */ 124 TypeResolver where(Map<TypeVariableKey, ? extends Type> mappings) { 125 return new TypeResolver(typeTable.where(mappings)); 126 } 127 128 private static void populateTypeMappings( 129 Map<TypeVariableKey, Type> mappings, Type from, Type to) { 130 if (from.equals(to)) { 131 return; 132 } 133 new TypeVisitor() { 134 @Override 135 void visitTypeVariable(TypeVariable<?> typeVariable) { 136 mappings.put(new TypeVariableKey(typeVariable), to); 137 } 138 139 @Override 140 void visitWildcardType(WildcardType fromWildcardType) { 141 if (!(to instanceof WildcardType)) { 142 return; // okay to say <?> is anything 143 } 144 WildcardType toWildcardType = (WildcardType) to; 145 Type[] fromUpperBounds = fromWildcardType.getUpperBounds(); 146 Type[] toUpperBounds = toWildcardType.getUpperBounds(); 147 Type[] fromLowerBounds = fromWildcardType.getLowerBounds(); 148 Type[] toLowerBounds = toWildcardType.getLowerBounds(); 149 checkArgument( 150 fromUpperBounds.length == toUpperBounds.length 151 && fromLowerBounds.length == toLowerBounds.length, 152 "Incompatible type: %s vs. %s", 153 fromWildcardType, 154 to); 155 for (int i = 0; i < fromUpperBounds.length; i++) { 156 populateTypeMappings(mappings, fromUpperBounds[i], toUpperBounds[i]); 157 } 158 for (int i = 0; i < fromLowerBounds.length; i++) { 159 populateTypeMappings(mappings, fromLowerBounds[i], toLowerBounds[i]); 160 } 161 } 162 163 @Override 164 void visitParameterizedType(ParameterizedType fromParameterizedType) { 165 if (to instanceof WildcardType) { 166 return; // Okay to say Foo<A> is <?> 167 } 168 ParameterizedType toParameterizedType = expectArgument(ParameterizedType.class, to); 169 if (fromParameterizedType.getOwnerType() != null 170 && toParameterizedType.getOwnerType() != null) { 171 populateTypeMappings( 172 mappings, fromParameterizedType.getOwnerType(), toParameterizedType.getOwnerType()); 173 } 174 checkArgument( 175 fromParameterizedType.getRawType().equals(toParameterizedType.getRawType()), 176 "Inconsistent raw type: %s vs. %s", 177 fromParameterizedType, 178 to); 179 Type[] fromArgs = fromParameterizedType.getActualTypeArguments(); 180 Type[] toArgs = toParameterizedType.getActualTypeArguments(); 181 checkArgument( 182 fromArgs.length == toArgs.length, 183 "%s not compatible with %s", 184 fromParameterizedType, 185 toParameterizedType); 186 for (int i = 0; i < fromArgs.length; i++) { 187 populateTypeMappings(mappings, fromArgs[i], toArgs[i]); 188 } 189 } 190 191 @Override 192 void visitGenericArrayType(GenericArrayType fromArrayType) { 193 if (to instanceof WildcardType) { 194 return; // Okay to say A[] is <?> 195 } 196 Type componentType = getComponentType(to); 197 checkArgument(componentType != null, "%s is not an array type.", to); 198 populateTypeMappings(mappings, fromArrayType.getGenericComponentType(), componentType); 199 } 200 201 @Override 202 void visitClass(Class<?> fromClass) { 203 if (to instanceof WildcardType) { 204 return; // Okay to say Foo is <?> 205 } 206 // Can't map from a raw class to anything other than itself or a wildcard. 207 // You can't say "assuming String is Integer". 208 // And we don't support "assuming String is T"; user has to say "assuming T is String". 209 throw new IllegalArgumentException("No type mapping from " + fromClass + " to " + to); 210 } 211 }.visit(from); 212 } 213 214 /** 215 * Resolves all type variables in {@code type} and all downstream types and returns a 216 * corresponding type with type variables resolved. 217 */ 218 public Type resolveType(Type type) { 219 checkNotNull(type); 220 if (type instanceof TypeVariable) { 221 return typeTable.resolve((TypeVariable<?>) type); 222 } else if (type instanceof ParameterizedType) { 223 return resolveParameterizedType((ParameterizedType) type); 224 } else if (type instanceof GenericArrayType) { 225 return resolveGenericArrayType((GenericArrayType) type); 226 } else if (type instanceof WildcardType) { 227 return resolveWildcardType((WildcardType) type); 228 } else { 229 // if Class<?>, no resolution needed, we are done. 230 return type; 231 } 232 } 233 234 @CanIgnoreReturnValue 235 Type[] resolveTypesInPlace(Type[] types) { 236 for (int i = 0; i < types.length; i++) { 237 types[i] = resolveType(types[i]); 238 } 239 return types; 240 } 241 242 private Type[] resolveTypes(Type[] types) { 243 Type[] result = new Type[types.length]; 244 for (int i = 0; i < types.length; i++) { 245 result[i] = resolveType(types[i]); 246 } 247 return result; 248 } 249 250 private WildcardType resolveWildcardType(WildcardType type) { 251 Type[] lowerBounds = type.getLowerBounds(); 252 Type[] upperBounds = type.getUpperBounds(); 253 return new Types.WildcardTypeImpl(resolveTypes(lowerBounds), resolveTypes(upperBounds)); 254 } 255 256 private Type resolveGenericArrayType(GenericArrayType type) { 257 Type componentType = type.getGenericComponentType(); 258 Type resolvedComponentType = resolveType(componentType); 259 return newArrayType(resolvedComponentType); 260 } 261 262 private ParameterizedType resolveParameterizedType(ParameterizedType type) { 263 Type owner = type.getOwnerType(); 264 Type resolvedOwner = (owner == null) ? null : resolveType(owner); 265 Type resolvedRawType = resolveType(type.getRawType()); 266 267 Type[] args = type.getActualTypeArguments(); 268 Type[] resolvedArgs = resolveTypes(args); 269 return newParameterizedTypeWithOwner(resolvedOwner, (Class<?>) resolvedRawType, resolvedArgs); 270 } 271 272 private static <T> T expectArgument(Class<T> type, Object arg) { 273 try { 274 return type.cast(arg); 275 } catch (ClassCastException e) { 276 throw new IllegalArgumentException(arg + " is not a " + type.getSimpleName()); 277 } 278 } 279 280 /** A TypeTable maintains mapping from {@link TypeVariable} to types. */ 281 private static class TypeTable { 282 private final ImmutableMap<TypeVariableKey, Type> map; 283 284 TypeTable() { 285 this.map = ImmutableMap.of(); 286 } 287 288 private TypeTable(ImmutableMap<TypeVariableKey, Type> map) { 289 this.map = map; 290 } 291 292 /** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */ 293 final TypeTable where(Map<TypeVariableKey, ? extends Type> mappings) { 294 ImmutableMap.Builder<TypeVariableKey, Type> builder = ImmutableMap.builder(); 295 builder.putAll(map); 296 for (Entry<TypeVariableKey, ? extends Type> mapping : mappings.entrySet()) { 297 TypeVariableKey variable = mapping.getKey(); 298 Type type = mapping.getValue(); 299 checkArgument(!variable.equalsType(type), "Type variable %s bound to itself", variable); 300 builder.put(variable, type); 301 } 302 return new TypeTable(builder.buildOrThrow()); 303 } 304 305 final Type resolve(TypeVariable<?> var) { 306 TypeTable unguarded = this; 307 TypeTable guarded = 308 new TypeTable() { 309 @Override 310 Type resolveInternal(TypeVariable<?> intermediateVar, TypeTable forDependent) { 311 if (intermediateVar.getGenericDeclaration().equals(var.getGenericDeclaration())) { 312 return intermediateVar; 313 } 314 return unguarded.resolveInternal(intermediateVar, forDependent); 315 } 316 }; 317 return resolveInternal(var, guarded); 318 } 319 320 /** 321 * Resolves {@code var} using the encapsulated type mapping. If it maps to yet another 322 * non-reified type or has bounds, {@code forDependants} is used to do further resolution, which 323 * doesn't try to resolve any type variable on generic declarations that are already being 324 * resolved. 325 * 326 * <p>Should only be called and overridden by {@link #resolve(TypeVariable)}. 327 */ 328 Type resolveInternal(TypeVariable<?> var, TypeTable forDependants) { 329 Type type = map.get(new TypeVariableKey(var)); 330 if (type == null) { 331 Type[] bounds = var.getBounds(); 332 if (bounds.length == 0) { 333 return var; 334 } 335 Type[] resolvedBounds = new TypeResolver(forDependants).resolveTypes(bounds); 336 /* 337 * We'd like to simply create our own TypeVariable with the newly resolved bounds. There's 338 * just one problem: We want to interoperate properly with the platform's built-in 339 * implementation of TypeVariable, but the behavior of the built-in implementation differs 340 * across platforms: 341 * 342 * - Under the JDK, the built-in TypeVariable's equals() method doesn't recognize instances 343 * of our TypeVariable implementation. 344 * 345 * - Under Android, it does. 346 * 347 * We want users to see the same behavior when they compare a built-in TypeVariable against 348 * ours as they do when they perform the same comparison in reverse. To provide that 349 * behavior on all platforms, TypeResolver must return the appropriate TypeVariable 350 * implementation in each of the three possible cases: 351 * 352 * 1. Under Android, the built-in TypeVariable implementation interoperates with ours. 353 * Therefore, we can always create our own TypeVariable. (One downside of our TypeVariable 354 * in some situations is that it does not support the AnnotatedType API. However, those 355 * situations don't arise under Android because Android does not provide the AnnotatedType 356 * API at all.) 357 * 358 * 2. Under the JDK, the built-in TypeVariable implementation does not interoperate with 359 * ours. Therefore, we have to be careful about whether we create our own TypeVariable: 360 * 361 * 2a. If the resolved types are identical to the original types, then we can return the 362 * original, identical JDK TypeVariable. By doing so, we sidestep the problem entirely. 363 * 364 * 2b. If the resolved types are different from the original types, things are trickier. The 365 * only way to get a TypeVariable instance for the resolved types is to create our own. The 366 * created TypeVariable will not interoperate with any JDK TypeVariable. But this is OK: We 367 * don't _want_ our new TypeVariable to be equal to the JDK TypeVariable because it has 368 * _different bounds_ than the JDK TypeVariable. And it wouldn't make sense for our new 369 * TypeVariable to be equal to any _other_ JDK TypeVariable, either, because any other JDK 370 * TypeVariable must have a different declaration or name. The only TypeVariable that our 371 * new TypeVariable _will_ be equal to is an equivalent TypeVariable that was also created 372 * by us. And that equality is guaranteed to hold because it doesn't involve the JDK 373 * TypeVariable implementation at all. 374 * 375 * NOTE: b/147144588 - Custom TypeVariables created by Guava do not preserve 376 * annotations. This is intentional. The semantics of annotation handling during 377 * type resolution are unclear and have changed across Java versions. Until there's 378 * a clear specification for what annotations should mean on resolved TypeVariables 379 * with modified bounds, annotation methods will throw 380 * UnsupportedOperationException. Frameworks requiring annotation preservation 381 * should use the original TypeVariable when bounds haven't changed. 382 */ 383 if (Types.NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY 384 && Arrays.equals(bounds, resolvedBounds)) { 385 return var; 386 } 387 return newArtificialTypeVariable( 388 var.getGenericDeclaration(), var.getName(), resolvedBounds); 389 } 390 // in case the type is yet another type variable. 391 return new TypeResolver(forDependants).resolveType(type); 392 } 393 } 394 395 private static final class TypeMappingIntrospector extends TypeVisitor { 396 397 private final Map<TypeVariableKey, Type> mappings = new HashMap<>(); 398 399 /** 400 * Returns type mappings using type parameters and type arguments found in the generic 401 * superclass and the super interfaces of {@code contextClass}. 402 */ 403 static ImmutableMap<TypeVariableKey, Type> getTypeMappings(Type contextType) { 404 checkNotNull(contextType); 405 TypeMappingIntrospector introspector = new TypeMappingIntrospector(); 406 introspector.visit(contextType); 407 return ImmutableMap.copyOf(introspector.mappings); 408 } 409 410 @Override 411 void visitClass(Class<?> clazz) { 412 visit(clazz.getGenericSuperclass()); 413 visit(clazz.getGenericInterfaces()); 414 } 415 416 @Override 417 void visitParameterizedType(ParameterizedType parameterizedType) { 418 Class<?> rawClass = (Class<?>) parameterizedType.getRawType(); 419 TypeVariable<?>[] vars = rawClass.getTypeParameters(); 420 Type[] typeArgs = parameterizedType.getActualTypeArguments(); 421 checkState(vars.length == typeArgs.length); 422 for (int i = 0; i < vars.length; i++) { 423 map(new TypeVariableKey(vars[i]), typeArgs[i]); 424 } 425 visit(rawClass); 426 visit(parameterizedType.getOwnerType()); 427 } 428 429 @Override 430 void visitTypeVariable(TypeVariable<?> t) { 431 visit(t.getBounds()); 432 } 433 434 @Override 435 void visitWildcardType(WildcardType t) { 436 visit(t.getUpperBounds()); 437 } 438 439 private void map(TypeVariableKey var, Type arg) { 440 if (mappings.containsKey(var)) { 441 // Mapping already established 442 // This is possible when following both superClass -> enclosingClass 443 // and enclosingclass -> superClass paths. 444 // Since we follow the path of superclass first, enclosing second, 445 // superclass mapping should take precedence. 446 return; 447 } 448 // First, check whether var -> arg forms a cycle 449 for (Type t = arg; t != null; t = mappings.get(TypeVariableKey.forLookup(t))) { 450 if (var.equalsType(t)) { 451 // cycle detected, remove the entire cycle from the mapping so that 452 // each type variable resolves deterministically to itself. 453 // Otherwise, an F -> T cycle will end up resolving both F and T 454 // nondeterministically to either F or T. 455 for (Type x = arg; x != null; x = mappings.remove(TypeVariableKey.forLookup(x))) {} 456 return; 457 } 458 } 459 mappings.put(var, arg); 460 } 461 } 462 463 // This is needed when resolving types against a context with wildcards 464 // For example: 465 // class Holder<T> { 466 // void set(T data) {...} 467 // } 468 // Holder<List<?>> should *not* resolve the set() method to set(List<?> data). 469 // Instead, it should create a capture of the wildcard so that set() rejects any List<T>. 470 private static class WildcardCapturer { 471 472 static final WildcardCapturer INSTANCE = new WildcardCapturer(); 473 474 private final AtomicInteger id; 475 476 private WildcardCapturer() { 477 this(new AtomicInteger()); 478 } 479 480 private WildcardCapturer(AtomicInteger id) { 481 this.id = id; 482 } 483 484 final Type capture(Type type) { 485 checkNotNull(type); 486 if (type instanceof Class) { 487 return type; 488 } 489 if (type instanceof TypeVariable) { 490 return type; 491 } 492 if (type instanceof GenericArrayType) { 493 GenericArrayType arrayType = (GenericArrayType) type; 494 return newArrayType(notForTypeVariable().capture(arrayType.getGenericComponentType())); 495 } 496 if (type instanceof ParameterizedType) { 497 ParameterizedType parameterizedType = (ParameterizedType) type; 498 Class<?> rawType = (Class<?>) parameterizedType.getRawType(); 499 TypeVariable<?>[] typeVars = rawType.getTypeParameters(); 500 Type[] typeArgs = parameterizedType.getActualTypeArguments(); 501 for (int i = 0; i < typeArgs.length; i++) { 502 typeArgs[i] = forTypeVariable(typeVars[i]).capture(typeArgs[i]); 503 } 504 return newParameterizedTypeWithOwner( 505 notForTypeVariable().captureNullable(parameterizedType.getOwnerType()), 506 rawType, 507 typeArgs); 508 } 509 if (type instanceof WildcardType) { 510 WildcardType wildcardType = (WildcardType) type; 511 Type[] lowerBounds = wildcardType.getLowerBounds(); 512 if (lowerBounds.length == 0) { // ? extends something changes to capture-of 513 return captureAsTypeVariable(wildcardType.getUpperBounds()); 514 } else { 515 // TODO(benyu): handle ? super T somehow. 516 return type; 517 } 518 } 519 throw new AssertionError("must have been one of the known types"); 520 } 521 522 TypeVariable<?> captureAsTypeVariable(Type[] upperBounds) { 523 String name = 524 "capture#" + id.incrementAndGet() + "-of ? extends " + Joiner.on('&').join(upperBounds); 525 return newArtificialTypeVariable(WildcardCapturer.class, name, upperBounds); 526 } 527 528 private WildcardCapturer forTypeVariable(TypeVariable<?> typeParam) { 529 return new WildcardCapturer(id) { 530 @Override 531 TypeVariable<?> captureAsTypeVariable(Type[] upperBounds) { 532 Set<Type> combined = new LinkedHashSet<>(asList(upperBounds)); 533 // Since this is an artificially generated type variable, we don't bother checking 534 // subtyping between declared type bound and actual type bound. So it's possible that we 535 // may generate something like <capture#1-of ? extends Foo&SubFoo>. 536 // Checking subtype between declared and actual type bounds 537 // adds recursive isSubtypeOf() call and feels complicated. 538 // There is no contract one way or another as long as isSubtypeOf() works as expected. 539 combined.addAll(asList(typeParam.getBounds())); 540 if (combined.size() > 1) { // Object is implicit and only useful if it's the only bound. 541 combined.remove(Object.class); 542 } 543 return super.captureAsTypeVariable(combined.toArray(new Type[0])); 544 } 545 }; 546 } 547 548 private WildcardCapturer notForTypeVariable() { 549 return new WildcardCapturer(id); 550 } 551 552 private @Nullable Type captureNullable(@Nullable Type type) { 553 if (type == null) { 554 return null; 555 } 556 return capture(type); 557 } 558 } 559 560 /** 561 * Wraps around {@code TypeVariable<?>} to ensure that any two type variables are equal as long as 562 * they are declared by the same {@link java.lang.reflect.GenericDeclaration} and have the same 563 * name, even if their bounds differ. 564 * 565 * <p>While resolving a type variable from a {@code var -> type} map, we don't care whether the 566 * type variable's bound has been partially resolved. As long as the type variable "identity" 567 * matches. 568 * 569 * <p>On the other hand, if for example we are resolving {@code List<A extends B>} to {@code 570 * List<A extends String>}, we need to compare that {@code <A extends B>} is unequal to {@code <A 571 * extends String>} in order to decide to use the transformed type instead of the original type. 572 */ 573 static final class TypeVariableKey { 574 private final TypeVariable<?> var; 575 576 TypeVariableKey(TypeVariable<?> var) { 577 this.var = checkNotNull(var); 578 } 579 580 @Override 581 public int hashCode() { 582 return Objects.hash(var.getGenericDeclaration(), var.getName()); 583 } 584 585 @Override 586 public boolean equals(@Nullable Object obj) { 587 if (obj instanceof TypeVariableKey) { 588 TypeVariableKey that = (TypeVariableKey) obj; 589 return equalsTypeVariable(that.var); 590 } else { 591 return false; 592 } 593 } 594 595 @Override 596 public String toString() { 597 return var.toString(); 598 } 599 600 /** Wraps {@code t} in a {@code TypeVariableKey} if it's a type variable. */ 601 static @Nullable TypeVariableKey forLookup(Type t) { 602 if (t instanceof TypeVariable) { 603 return new TypeVariableKey((TypeVariable<?>) t); 604 } else { 605 return null; 606 } 607 } 608 609 /** 610 * Returns true if {@code type} is a {@code TypeVariable} with the same name and declared by the 611 * same {@code GenericDeclaration}. 612 */ 613 boolean equalsType(Type type) { 614 if (type instanceof TypeVariable) { 615 return equalsTypeVariable((TypeVariable<?>) type); 616 } else { 617 return false; 618 } 619 } 620 621 private boolean equalsTypeVariable(TypeVariable<?> that) { 622 return var.getGenericDeclaration().equals(that.getGenericDeclaration()) 623 && var.getName().equals(that.getName()); 624 } 625 } 626}