类型擦除、覆盖和泛型 [英] Type erasure, overriding and generics

查看:25
本文介绍了类型擦除、覆盖和泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我解释一下为什么

Can someone explain to me why

@Override
public void fooMethod(Class<?> c)

不会覆盖

public void fooMethod(Class c)

并给我以下错误:

 - Name clash: The method fooMethod(Class<?>) 
of type SubClass has the same erasure as fooMethod(Class) of 
type SuperClass but  does not override it

 - The method fooMethod(Class<?>) of type 
SubClass must override a superclass method

?

java -version"说Java(TM) 2 运行时环境,标准版(构建 1.5.0_16-b06-284).至于代码片段,上面已经差不多了;上面的扩展了下面的.

"java -version" says Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284). As for the code snippet, it's already above, pretty much; the above extends the one below.

推荐答案

fooMethod(Class) 的签名与 fooMethod(Class)<的签名相同/code> 擦除后,由于 Class 的擦除只是 Class (JLS 4.6).因此,fooMethod(Class)fooMethod(Class) 的子签名,但不是相反的(JLS 8.4.2).

The signature of fooMethod(Class<?>) is the same as the signature of fooMethod(Class) after erasure, since the erasure of Class<?> is simply Class (JLS 4.6). Hence, fooMethod(Class) is a subsignature of the fooMethod(Class<?>) but not the opposite (JLS 8.4.2).

要使用实例方法覆盖,您需要覆盖方法是覆盖方法的子签名 (JLS 8.4.8.1).这显然不是这里的情况.

For overriding with instance methods you need the overriding method to be a subsignature of the overridden method (JLS 8.4.8.1). This is clearly not the case here.

既然我们已经确定了根据 JLS,您的子类方法不会覆盖超类方法的事实,让我们看看发生类型擦除时的运行时影响.我们现在有两个看起来完全相同的方法(相同的名称,相同的参数类型)但不会相互覆盖.如果它们不覆盖,它们必须作为单独的方法在子类型上可用,但它们具有相同的运行时签名:冲突.所以Java必须禁止它.

Now that we have established the fact that your subclass method doesn't override the superclass method according to the JLS, let's look at the runtime implications when type erasure has occured. We now have two methods that look exactly the 'same' (same name, same parameter types) but do not override each other. If they don't override, they must be both available on the subtype as separate methods, but they have identical runtime signatures: conflict. So Java has to disallow it.

使用原始参数类型覆盖泛型参数类型是允许的,因为原始类型的存在正是出于这个原因:它们是一种方便的机制,具有特定的不健全的类型规则以适应与遗留代码的交互.所以这里的类型系统将决定子类方法确实覆盖超类方法,它们在类型擦除后是相同的,我们永远不会有冲突.因此,该库可以独立于现有的非通用代码进行泛化.

Overriding generic parameter types using raw parameter types is allowed because raw types exist just for this reason: they are a convenient mechanism with specific unsound type rules to accommodate interaction with legacy code. So the type system here will decide that the subclass method does override the superclass one, they are identical after type erasure and we can never have a conflict. As a consequence of this libraries can be generified independently of existing non-generic code.

这篇关于类型擦除、覆盖和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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