用泛型返回对象子类 [英] Returning an objects subclass with generics

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

问题描述

使用抽象类我想定义一个返回子类this的方法:

With an abstract class I want to define a method that returns "this" for the subclasses:

public abstract class Foo {
    ...
    public <T extends Foo> T eat(String eatCake) {
        ...
        return this;
    }
}  

public class CakeEater extends Foo {}

我希望能够做到这样的事情:

I want to be able to do things like:

CakeEater phil = new CakeEater();
phil.eat("wacky cake").eat("chocolate cake").eat("banana bread");

可以说,香蕉面包会抛出IllegalArgumentException异常,并显示Not a cake!。

Arguably banana bread would throw an IllegalArgumentException with the message "Not a cake!"

推荐答案

public abstract class Foo<T extends Foo<T>>  // see ColinD's comment
{
    public T eat(String eatCake) 
    {
        return (T)this;
    }
}

public class CakeEater extends Foo<CakeEater> 
{
    public void f(){}
}

编辑

要求子类以某种方式运行超出静态类型可检查的范围是没有问题的。我们一直这样做 - 简单的英语页面和页面来指定你如何编写一个子类。

There is no problem to require subclass behave in a certain way that's beyond what static typing can check. We do that all the time - pages and pages of plain english to specify how you write a subclass.

另一个提议的协同返回类型的解决方案必须做同样的 - 用简单的英语要求子类实现者返回这个的类型。该要求不能由静态类型来指定。

The other proposed solution, with covariant return type, must do the same - asking subclass implementers, in plain english, to return the type of this. That requirement cannot be specified by static typing.

这篇关于用泛型返回对象子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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