Java泛型类型参数隐藏 [英] Java generics type parameter hiding

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

问题描述

我定义了一个类:

  class Foo< I extends Bar&可比< I>> {
}

编译器抱怨 I I隐藏。我想第二次出现在定义中的 I 隐藏在第一个范围内,就好像变量 I 可以是分配给两种不同的类型。如何正确地做到这一点?



编辑:

这是一个内部类。完整的代码可以是:

  class Baz< I> {
class Foo< I extends Bar&可比< I>> {
}
}

现在的问题是,如果我重新提名内 J ,我不确定 I J 实际上是相同的类型。

解决方案

使内部类参数化:

  class Baz< I extends Bar&可比< I>> {
class Foo {
}
}

(非静态嵌套)类, Baz 声明中定义的 I 仍然在 Foo ,因为每个 Foo 都会隐式引用其外部 Baz 实例。


I'm defining a class:

class Foo<I extends Bar & Comparable<I>> {
}

the compiler is complaining about I being hidden by I. I guess the second time I appears in the definition is hiding in scope the first one, as if variable I could be assigned to two different types. How to do it correctly?

Edit:

this is an inner class. the full code can be:

class Baz<I> {
    class Foo<I extends Bar & Comparable<I>> {
    }
}

now the problem is that if I re-nominate inner I to J, i'm not sure that I and J are actually the same types.

解决方案

Don't make the inner class parameterized:

class Baz<I extends Bar & Comparable<I>> {
   class Foo {
   }
}

As an inner (non-static nested) class, I as defined in the Baz declaration will still have meaning in Foo, since every Foo will have an implicit reference to its outer Baz instance.

这篇关于Java泛型类型参数隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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