6

Type erasure is the process of removing generic information for backward compatibility on compiled class. Then, I can't know what type of class are the objects in a generic class, but in an inherited class, for example:

package generics.testing;

class Box<T> {
    private T value;

    public Box() {
        System.out.println("GenericSuperClass: " + getClass().getGenericSuperclass());
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}

class IntegerBox extends Box<Integer> {}

public class GenericsTesting {
    public static void main(String[] args) {
        Box<String> box = new Box<>();
        IntegerBox ibox = new IntegerBox();
    }
}

I get:

GenericSuperClass: class java.lang.Object
GenericSuperClass: generics.testing.Box<java.lang.Integer>

My question is, why is that information generics.testing.Box<java.lang.Integer> preserved and where is stored?

Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
rvillablanca
  • 1,355
  • 3
  • 15
  • 32
  • 1
    You might find that interesting read: https://github.com/google/guava/wiki/ReflectionExplained (specifically part about TypeToken implementation) – Artur Biesiadowski May 18 '16 at 14:33
  • 1
    It is stored into your class itself as it is part of its declaration, simply launch javap generics.testing.IntegerBox, you will see it appear – Nicolas Filotto May 18 '16 at 14:38
  • 1
    duplicate of https://stackoverflow.com/questions/2320658/why-are-not-all-type-information-erased-in-java-at-runtime – Jiri Kremser May 18 '16 at 14:39

0 Answers0