how type variable allowing wrong type?
Asked Answered
T

1

12
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.

Trillium answered 25/9, 2017 at 8:15 Comment(4)
I cannot compile your example: Bound mismatch: The generic method typeVarType(T, A) of type TestTypeVariable is not applicable for the arguments (String, Integer). The inferred type Integer is not a valid substitute for the bounded parameter <A extends T> Which is what I would expect. Did you compile the source successfully?Scheider
With the compiler resolving T to Object and A to Integer, there is no issue.Zinnia
@Scheider It passes compilation in Java 8, but not in Java 7.Ultann
This is already being answered in this post #12475550Dorsman
B
15

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.
Blunk answered 25/9, 2017 at 8:18 Comment(6)
It compiles fine. typeVarType("string", i); has T=Object, A=Integer .Unplaced
it is compilable and runable. getClass() i just used to print run-time type of an object.but thats not an issue. main point is how java allowing integer type for an string upper bounded typeTrillium
@Unplaced That happens when one believes in other comments without further checking. I thought "T should be Object" myself ... thanks, and updated.Blunk
It compiles fine in Java 8, but doesn't pass compilation in Java 7. In this case I think it makes more sense for it not to pass compilation, since <T,A extends T> makes no sense (due to type erasure).Ultann
Of course, the inferred type for T could also be Object & Serializable & Comparable<?>Hemorrhoidectomy
I wish you could quote the JLS here, i swear given this on an interview I would say it failsFunctionary

© 2022 - 2024 — McMap. All rights reserved.