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 com.google.common.annotations.Beta;
020import java.lang.reflect.Type;
021import java.lang.reflect.TypeVariable;
022import org.checkerframework.checker.nullness.qual.Nullable;
023
024/**
025 * Captures a free type variable that can be used in {@link TypeToken#where}. For example:
026 *
027 * <pre>{@code
028 * static <T> TypeToken<List<T>> listOf(Class<T> elementType) {
029 *   return new TypeToken<List<T>>() {}
030 *       .where(new TypeParameter<T>() {}, elementType);
031 * }
032 * }</pre>
033 *
034 * @author Ben Yu
035 * @since 12.0
036 */
037@Beta
038public abstract class TypeParameter<T> extends TypeCapture<T> {
039
040  final TypeVariable<?> typeVariable;
041
042  protected TypeParameter() {
043    Type type = capture();
044    checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type);
045    this.typeVariable = (TypeVariable<?>) type;
046  }
047
048  @Override
049  public final int hashCode() {
050    return typeVariable.hashCode();
051  }
052
053  @Override
054  public final boolean equals(@Nullable Object o) {
055    if (o instanceof TypeParameter) {
056      TypeParameter<?> that = (TypeParameter<?>) o;
057      return typeVariable.equals(that.typeVariable);
058    }
059    return false;
060  }
061
062  @Override
063  public String toString() {
064    return typeVariable.toString();
065  }
066}