Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to resolve a type in Java?

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.

  • Type variables or parameterized types need to be created for this form of reflection to work because they can't be loaded, because they don't really "exist" at runtime?
  • So if something exists at runtime, it can be "resolved"? By the classloader?

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
  • This I don't really get at all. Not sure what this code is doing.
like image 315
Dmitry Minkovsky Avatar asked Jul 28 '15 19:07

Dmitry Minkovsky


1 Answers

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.

like image 69
Sotirios Delimanolis Avatar answered Oct 15 '22 00:10

Sotirios Delimanolis