1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.reflect;
18
19import static com.google.common.base.Preconditions.checkArgument;
20
21import com.google.common.annotations.Beta;
22
23import java.lang.reflect.Type;
24import java.lang.reflect.TypeVariable;
25
26import javax.annotation.Nullable;
27
28/**
29 * Captures a free type variable that can be used in {@link TypeToken#where}.
30 * For example:
31 *
32 * <pre>   {@code
33 *   static <T> TypeToken<List<T>> listOf(Class<T> elementType) {
34 *     return new TypeToken<List<T>>() {}
35 *         .where(new TypeParameter<T>() {}, elementType);
36 *   }}</pre>
37 *
38 * @author Ben Yu
39 * @since 12.0
40 */
41@Beta
42public abstract class TypeParameter<T> extends TypeCapture<T> {
43
44  final TypeVariable<?> typeVariable;
45
46  protected TypeParameter() {
47    Type type = capture();
48    checkArgument(type instanceof TypeVariable, "%s should be a type variable.", type);
49    this.typeVariable = (TypeVariable<?>) type;
50  }
51
52  @Override public final int hashCode() {
53    return typeVariable.hashCode();
54  }
55
56  @Override public final boolean equals(@Nullable Object o) {
57    if (o instanceof TypeParameter) {
58      TypeParameter<?> that = (TypeParameter<?>) o;
59      return typeVariable.equals(that.typeVariable);
60    }
61    return false;
62  }
63
64  @Override public String toString() {
65    return typeVariable.toString();
66  }
67}
68