如何解释这个Java泛型类型定义?
下面是如何解释这个Java泛型类型定义?,java,netty,Java,Netty,下面是netty4.0.24框架中的一些代码片段。解释Btype参数有点混乱 public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable { ... } 公共抽象类AbstractBootstrap实现可克隆 { ... } 我认为它基本上是一个有两个参数的类,B和C。第一个参数(B)必须是扩展类本身
netty4.0.24
框架中的一些代码片段。解释B
type参数有点混乱
public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable
{
...
}
公共抽象类AbstractBootstrap实现可克隆
{
...
}
我认为它基本上是一个有两个参数的类,B和C。第一个参数(B)必须是扩展类本身(或子类)的东西,第二个参数(C)必须扩展通道
用它来思考有点奇怪,但是您可以有一个运行相同类型对象的类
排序回答:它的参数是自身和通道。“B”似乎代表子类AbstractBootstrap本身。它认为(imho)这是一个奇怪的声明,使它在泛型参数中出现子类
请查看eclipse中具有子类型层次结构的子类,您可能会发现如下内容
class AnyClass extends AbstractBootstrap<AnyClass,AChannel>
class AnyClass扩展了AbstractBootstrap
所以在本例中,我们在其泛型声明中重复“AnyClass”这可能被解释为 在这种情况下,类型参数
B
的主要目的是能够引用抽象类中的继承类型。例如,AbstractBootstrap
类有一个方法
B channel(Class<? extends C> channelClass)
及
旁白:我一直主张类型安全,但一旦嵌套了这些类型参数,您可能最终会得到类或方法声明,这些声明意味着类型边界很难手动检查。因此,只有在可读性和类型安全性之间的权衡真正合理时,才应该使用它们 通读这篇文章,我似乎可以让类声明
classserverbootstrap扩展AbstractBootstrap
,因为Bootstrap
有效地扩展了AbstractBootstrap
,并在其自己的声明中引用了它自己。这是否正确?@MirroredFate由于Channel
vs.ServerChannel
类型参数,这将不起作用。但原则上,可以创建“不直观”(或明显错误)的参数化,比如
class Bootstrap extends AbstractBootstrap<Bootstrap,Channel>
class ServerBootstrap extends AbstractBootstrap<ServerBootstrap,ServerChannel>
public class BootstrapExample
{
public static void main(String[] args)
{
// On a Bootstrap, calling the 'channel' method
// will return a Bootstrap
Bootstrap bootstrap = new Bootstrap();
Bootstrap resultBootstrap =
bootstrap.channel(null);
// On a ServerBootstrap, calling the 'channel' method
// will return a ServerBootstrap
ServerBootstrap serverBootstrap = new ServerBootstrap();
ServerBootstrap resultSeverBootstrap =
serverBootstrap.channel(null);
}
}
abstract class AbstractBootstrap<
B extends AbstractBootstrap<B, C>,
C extends Channel> implements Cloneable
{
public B channel(Class<? extends C> channelClass)
{
return null;
}
}
class Bootstrap extends AbstractBootstrap<Bootstrap,Channel> {}
class ServerBootstrap
extends AbstractBootstrap<ServerBootstrap,ServerChannel> {}
class Channel {}
class ServerChannel extends Channel {}