What does it mean to resolve a type in Java?
Here are some usage examples with my attempts at making sense of them:
From Field#getGenericType():
If the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved.
From TypeToken#resolveType():
Resolves the given type against the type context represented by this type. For example:
new TypeToken<List<String>>() {}.resolveType(
List.class.getMethod("get", int.class).getGenericReturnType())
=> String.class
Regarding your first question, consider a field declaration like
public List<String> parameterizedField;
The JVM does not maintain an object representing the type List<String> (as it would a Class object). It therefore needs to create a new Type (ParameterizedType in this case) object representing that type and return it (it might also cache it for future use). It will do the same for
public E genericField;
creating a TypeVariable object in this case.
For
public String regularTypeField;
however, the type is known, the JVM maintains a Class object for String and therefore only needs to return that.
In the second case, the type token hack
new TypeToken<List<String>>() {}
internally creates a Type that represents List<String> which would otherwise not be possible to retrieve directly because of type erasure.
The resolveType call checks the Type you give it and resolves it based on the TypeToken's type argument.
In your example, the getGenericReturnType() invoked will return a Type representing the type variable declared in the List class. Since you've parameterized List with String, resolveType() will return String. It binds the type argument you provided in the type token to its corresponding type variable used in methods or fields.
Had you used
new TypeToken<List<String>>() {}.
resolveType(Iterator.class.getMethod("next").getGenericReturnType())
it would have returned E because that type variable is unrelated to the one you bound in the type token.
The uses of resolved in both cases is different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With