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