如何解释这个Java泛型类型定义?

smw*_*dia 9 java netty

下面是netty 4.0.24框架中的一些代码片段.解释B类型参数有点令人困惑.

public abstract class AbstractBootstrap<B extends AbstractBootstrap<B, C>, C extends Channel> implements Cloneable
{
 ...
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*o13 4

这可能被解释为奇怪的重复模板模式的一种形式。

在这种情况下,类型参数的主要目的B是能够引用抽象类中的继承类型。例如,该类AbstractBootstrap有一个方法

B channel(Class<? extends C> channelClass)
Run Code Online (Sandbox Code Playgroud)

因此,这里的返回类型是作为第一个类型参数给出的任何类型。查看该类的已知实现AbstractBoottrap,我们会发现

class Bootstrap extends AbstractBootstrap<Bootstrap,Channel>
Run Code Online (Sandbox Code Playgroud)

class ServerBootstrap extends AbstractBootstrap<ServerBootstrap,ServerChannel>
Run Code Online (Sandbox Code Playgroud)

他们接收“他们自己”作为第一个类型参数。因此channel这些实现的方法将返回“类型本身”。

这里显示了一个可能的使用场景(使用一些虚拟类使其可编译并指出相关部分):

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 {}
Run Code Online (Sandbox Code Playgroud)

旁白:我一直提倡类型安全,但是一旦这些类型参数被嵌套,您最终可能会得到隐含类型界限的类或方法声明,而这些类型界限很难手动检查。因此,只有当可读性和类型安全性之间的权衡确实合理时才应该使用它们。