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