简体   繁体   中英

What is a “free type variable” in the context of Guava's TypeToken documentation?

I am trying to create a Map with keys that are types. To support generic types, I need something like Guava's TypeToken .

However, I and am confused by some of the terminology in the constructors' documentation. For example, the second constructor:

Constructs a new type token of T while resolving free type variables in the context of declaringClass.

What is a "free type variable"? What is the "declaringClass?"

In the class-level javadoc , they give a usage example for that constructor

//                 free type variable
//                         v
abstract class IKnowMyType<T> {
    TypeToken<T> type = new TypeToken<T>(getClass()) {};
}
new IKnowMyType<String>() {}.type => String

You wouldn't typically be able to get the String . But, here, getClass returns a anonymous subclass which has IKnowMyType<String> as its superclass. You can therefore extract the String with the typical type token hack:

Type superclass = getClass().getGenericSuperclass();
Type actualTypeArgument = ((ParameterizedType) superclass).getActualTypeArguments()[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM