java:使用Raw类型作为方法参数会擦除参数成员中所有已参数化的类型信息 [英] java: Use of Raw type as method parameter errases all parametrized type information in parameter members

查看:136
本文介绍了java:使用Raw类型作为方法参数会擦除参数成员中所有已参数化的类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释为什么如果我在test()方法中使用原始类型A,则类型列表上的get()方法将返回一个Object而不是一个B.:

Please explain me why if I use the raw type A in the method test() , the get() method on my typed list returns an Object and not a B.:

public class test
{
    public class B{}
    public class C{}

    public class A<T extends C>
    {
        private List<B> aBList;

        public List<B> mGetBList()
        {
            return aBList;
        }
    }

    public test(A pA) // Use of raw type - this is bad, I know!
    {
        B lB = pA.mGetBList().get(0); // Compile error: Type mismatch: 
                                      // cannot convert from Object to test.B   

    }
}

如果我声明

public test(A<?> pA)

get()方法返回预期的B.

the get() method returns a B as expected.

推荐答案

+1以获得有趣的测试用例.

+1 for interesting test case.

看起来像擦除会擦除所有内容,因此在这种情况下,您最终会得到结果.

Looks like erasure erases everything, so in this case, you end up with.

public List mGetBList()

擦除List会导致public Object get( int ),这当然不能分配给B.

And erasure of List will result in public Object get( int ), which, of course, cannot be assigned to B.

如果方法签名中对原始类型的需求不大,请使用您提供的通用形式,否则将对象强制转换为B

If there is no strong need for raw type in method signature, use generic form that you have provided, otherwise cast the object to B

B lB = (B) pA.mGetBList().get(0);

这篇关于java:使用Raw类型作为方法参数会擦除参数成员中所有已参数化的类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆