Java: Why doesn't the generic class apply the same type?

I have:


    public final class SomeClass<L, R>{
    ....
    }

If I do this:


    public final class SomeClass<L, R>{
    ....

    public someMethod(Object obj)
    {
    SomeClass other<L, R> = (SomeClass<L, R>) obj;
    ....
    }
    ....
    SomeClass<String, String> firstObject = new SomeClass<String, String>();
    SomeClass<Integer, Integer> secondObjec = new SomeClass<Integer, Integer>();
    firstObject.someMethod(secondObject );
    ...

He does not throw an exception casting, even if the types Land Rdifferent from firstObjectbefore secondObject. Why?

+4
source share
2 answers

This code will be compiled because you pass the object as a parameter and explicitly point it to SomeClass<L, R>. Due to the erasure type, this will work at runtime if you pass any instance SomeClass, because all the generic types will disappear by then. I assume that at compile time you get a warning Type safety: Unchecked cast from Object to SomeClass<String, String>(if you did not specify @SuppressWarnings("unchecked")).

, , , :

public someMethod(SomeClass<L, R> obj)
+4

Java . .

+2

All Articles