Roxana
Roxana

Reputation: 1581

Java: Why generic class does not enforce same type?

I have:


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

If I do:


    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 );
    ...

It does not throw casting exception, even if the L and R types are different from firstObject to secondObject. Why?

Upvotes: 4

Views: 94

Answers (2)

xlecoustillier
xlecoustillier

Reputation: 16351

This code will compile because you pass an object as a parameter, and cast it explicitly into SomeClass<L, R>. Due to type erasure, this will work at runtime as long as you pass any instance of SomeClass, because all generic types will have disappeared by then. I'm guessing you're getting a Type safety: Unchecked cast from Object to SomeClass<String, String> warning during compilation (unless you specified @SuppressWarnings("unchecked")).

To avoid this, you'll have to specify the type of the object you're allowed to pass as a parameter, doing for instance:

public someMethod(SomeClass<L, R> obj)

Upvotes: 4

Olivier Meurice
Olivier Meurice

Reputation: 562

Generics in Java are checked by the compiler. It is not taken into account at runtime.

Upvotes: 2

Related Questions