Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why type variable is non-reifiable type in java

I'm currently learning java generics and below is a list of types in java that is non-reifiable.

A type is not reifiable if it is one of the following:

• A type variable (such as T)

• A parameterized type with actual parameters (such as List<Number>, ArrayList<String>, or Map<String, Integer>)

• A parameterized type with a bound (such as List<? extends Number> or Comparable<? super String>)

I understand why parameterized type with actual parameter and parameterized type with bound is non-refieable, because after runtime erasure, the only type information left is List, but why is type variable (such as T) a non-reifiable type? I thought at runtime, after type erasure, T would become Object (given T is an unbound type parameter), so the type information is available.

Is there something wrong with my understanding?

like image 499
Thor Avatar asked Jun 18 '18 05:06

Thor


2 Answers

The docs state that

A non-reifiable type does not have all of its information available at runtime.

The type of T at runtime is Object so information is lost. An example of the information that is lost is how an object can be created. Consider this class:

public class A {
    private int a;
    public A() {
        a = 5;
    }
}

Now look at this not compiling code:

public class Generic<T> {
    T foo() {
        return new T(); //Compiler Error!
    }
}

If this was allowed and you were instantiating a Generic<A> g = new Generic<>(); and calling g.foo(), the constructor of T could not be called, because, at runtime, T is only known as Object. Therefore, an valid instance of A cannot be created and returned. You even cannot be sure which information a constructor of T needs. The information how T can be constructed is lost.

That is one reason why type parameters must be non-reifiable types.

like image 196
Tobias Avatar answered Oct 11 '22 23:10

Tobias


An object is reifiable when its typing information is not lost at compile time. Some operations are not allowed on non-reifiable objects. For example, we can not do an instance of.

Generic types are not reifiable and that's why we can not do such a

 List <Conference> instance

This would be practical in some cases but we must not forget that the JDK must be backward compatible from one version to another. This constraint explains some limitations in implementations.

A Java type is reifiable if it is represented completely during execution (without erasure Of type) :

 primitive type
 non-parametric type
 parametric type in which all arguments of type are unbounded jokers (List <?>)
 type "raw" (List)
 table whose type of elements is reifiable
like image 42
Adam Perea Avatar answered Oct 11 '22 23:10

Adam Perea