类型删除,覆盖和泛型 [英] Type erasure, overriding and generics
问题描述
@Override
public void fooMethod(Class<?> c)
不会覆盖
public void fooMethod(Class c)
并且给我以下错误:
- 名称冲突:SubClass类型的fooMethod(Class<?>)
方法与fooMethod(Class)
类型SuperClass但不覆盖它
-
SubClass类型的方法fooMethod(Class<>)必须覆盖超类方法
$ b
编辑: java -version
说
Java(TM)2运行时环境,标准版(版本1.5.0_16-b06-284)。至于代码片段,它已经在上面了,非常多;上面的代码扩展了下面的代码。
fooMethod(Class)
的签名相同,因为 Class <?> code>就是
Class
( JLS 4.6 )。因此, fooMethod(Class)
是 fooMethod(Class <?>)
的子签名,但不是相反的 JLS 8.4.2 )。
要覆盖实例方法,您需要重写方法作为重写方法的子签名( JLS 8.4.8.1 )。这显然不是这种情况。
现在我们已经确定了子类方法不会根据JLS覆盖超类方法,让我们来看看发生类型擦除时的运行时影响。我们现在有两种方法看起来完全相同(相同的名称,相同的参数类型),但不会相互覆盖。如果它们不覆盖,它们必须作为单独的方法在子类型上可用,但它们具有相同的运行时签名:冲突。因此,Java必须禁止它。
使用原始参数类型覆盖通用参数类型是允许的,因为原始类型仅仅因为这个原因而存在:它们是一种方便的机制,具有特定的不合适的类型规则以适应与旧代码的交互。因此,这里的类型系统将决定子类方法不会覆盖超类,它们在类型擦除之后是相同的,我们永远不会有冲突。由于这些库可以独立于现有的非泛型代码而被基因化。 Can someone explain to me why doesn't override and gives me the following errors instead: ? Edit: " The signature of 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. 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屋!@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
" 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<?>)
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).