Java generics - Why “incompatible types” compilati

2019-04-11 13:13发布

This question already has an answer here:

Please notice the code below doesn't compile, failing on the method result assignment: String s = a.method("abc");.

The compilation error: incompatible types: java.lang.Object cannot be converted to java.lang.String

But, when changing A a to A<?> a or to A<Object> a, the compilation passes.

* Please notice that the type <T> in the method is different than the type <O> in the class.

Any idea what the compilation error? Also, why the generic definition in variable a solves the compilation issue?

class A<O>
{
    O something;

    <T> T method(T t)
    {
        return t;
    }

    static void testJavaStrangeGenericDefinitionBehavior()
    {
        A a = null;

        String s = a.method("abc");
    }
}

2条回答
Viruses.
2楼-- · 2019-04-11 14:02

It's because Java's type erasure meaning for backward compatibility all generic type declarations exist only in source code and after compilation they are converted to Object references and proper casts behind the scenes so the JVM in this case is confused that you meant O or T.

查看更多
别忘想泡老子
3楼-- · 2019-04-11 14:08
A a = null;

should be:

A<String> a = null; // or better yet, new A<String>();

Although, you could substitute any class for String since, as you say, the T and O generics are different types.

Once you remove the generic parameter, you lose all the generics in your method call, which essentially becomes equivalent to calling:

Object method(Object t);
查看更多
登录 后发表回答