Mario Ishac
Mario Ishac

Reputation: 5877

What is the difference between the class `Class` and the class `Type` in java?

I've read this SO question that talks about the difference between classes and types in java

However, this talks about classes declared with the class keyword rather than the actual class Class in java. In Java, I can have a Class<T> where T is a class/interface/array type (and for primitives, T would be the autoboxed class, but the instance of Class<T> would be associated with the primitive type, such as int.class). Point is, Class is used with more than just class types.

What is the difference between the classClass and interface Type? When would I ever use Type in a java program?

Upvotes: 2

Views: 2203

Answers (1)

Radiodef
Radiodef

Reputation: 37845

Type is a superinterface of Class. You won't generally need to use it unless you're doing reflection with generic types.

As an example, we can get the type of a field using Field.getType():

Class<?> c =
    String.class.getField("CASE_INSENSITIVE_ORDER")
        .getType();

The problem is that String.CASE_INSENSITIVE_ORDER is actually a Comparator<String>, and the above code will only get us Comparator.class. This doesn't work for us if we needed to know what the type argument was.

Type and its uses were added in Java 1.5 (along with generics) for this type of situation. We could instead use the method Field.getGenericType():

Type t =
    String.class.getField("CASE_INSENSITIVE_ORDER")
        .getGenericType();

In this case, it would return an instance of ParameterizedType, with Comparator.class as its raw type and String.class in its type arguments:

ParameterizedType pt = (ParameterizedType) t;
pt.getRawType(); // interface java.util.Comparator
pt.getActualTypeArguments(); // [class java.lang.String]

This part of the API isn't very well developed, but there are some better ones built around it, like Guava TypeToken.

Upvotes: 4

Related Questions