001/* 002 * Copyright (C) 2011 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; 018 019import java.lang.reflect.Type; 020import java.lang.reflect.TypeVariable; 021import org.jspecify.annotations.Nullable; 022 023/** 024 * Captures a free type variable that can be used in {@link TypeToken#where}. For example: 025 * 026 * {@snippet : 027 * static <T> TypeToken<List<T>> listOf(Class<T> elementType) { 028 * return new TypeToken<List<T>>() {} 029 * .where(new TypeParameter<T>() {}, elementType); 030 * } 031 * } 032 * 033 * @author Ben Yu 034 * @since 12.0 035 */ 036/* 037 * A nullable bound would let users create a TypeParameter instance for a parameter with a nullable 038 * bound. However, it would also let them create `new TypeParameter<@Nullable T>() {}`, which 039 * wouldn't behave as users might expect. Additionally, it's not clear how the TypeToken API could 040 * support even a "normal" `TypeParameter<T>` when `<T>` has a nullable bound. (See the discussion 041 * on TypeToken.where.) So, in the interest of failing fast and encouraging the user to switch to a 042 * non-null bound if possible, let's require a non-null bound here. 043 * 044 * TODO(cpovirk): Elaborate on "wouldn't behave as users might expect." 045 */ 046public abstract class TypeParameter<T> extends TypeCapture<T> { 047 048 final TypeVariable<?> typeVariable; 049 050 protected TypeParameter() { 051 Type type = capture(); 052 checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type); 053 this.typeVariable = (TypeVariable<?>) type; 054 } 055 056 @Override 057 public final int hashCode() { 058 return typeVariable.hashCode(); 059 } 060 061 @Override 062 public final boolean equals(@Nullable Object o) { 063 if (o instanceof TypeParameter) { 064 TypeParameter<?> that = (TypeParameter<?>) o; 065 return typeVariable.equals(that.typeVariable); 066 } 067 return false; 068 } 069 070 @Override 071 public String toString() { 072 return typeVariable.toString(); 073 } 074}