how type variable allowing wrong type?

Viewed 745
package org.my.java;

public class TestTypeVariable {

    static <T,A extends T> void typeVarType(T t, A a){
        System.out.println(a.getClass());
        System.out.println(t.getClass());
    }

    public static void main(String[] s){
        int i= 1;
        typeVarType("string", i);
    }
}

when run, following is the output :

class java.lang.Integer
class java.lang.String

How can A be of type Integer when it has been already upper-bounded to String?

Please explain me on it.

1 Answers

Two things here:

  • there is a simple solution to the "bad" typing: T isn't String but Object. And Integer extends Object. But please note: this only works with the "enhanced" type inference capabilities of Java8. With Java7, your input will not compile!
  • misconception on your end: getClass() happens at runtime, and therefore returns the specific class of the objects passed - independent on what the compiler thinks about generics at compile time.
Related