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 javax.annotation.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 *   }}</pre>
032 *
033 * @author Ben Yu
034 * @since 12.0
035 */
036@Beta
037public abstract class TypeParameter<T> extends TypeCapture<T> {
038
039  final TypeVariable<?> typeVariable;
040
041  protected TypeParameter() {
042    Type type = capture();
043    checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type);
044    this.typeVariable = (TypeVariable<?>) type;
045  }
046
047  @Override
048  public final int hashCode() {
049    return typeVariable.hashCode();
050  }
051
052  @Override
053  public final boolean equals(@Nullable Object o) {
054    if (o instanceof TypeParameter) {
055      TypeParameter<?> that = (TypeParameter<?>) o;
056      return typeVariable.equals(that.typeVariable);
057    }
058    return false;
059  }
060
061  @Override
062  public String toString() {
063    return typeVariable.toString();
064  }
065}