【问题标题】:Method chaining + inheritance don’t play well together?方法链 + 继承不能很好地结合在一起?
【发布时间】:2010-11-07 08:36:41
【问题描述】:

This question has been asked in a C++ context 但我对 Java 很好奇。对虚拟方法的担忧不适用(我认为),但如果你有这种情况:

abstract class Pet
{
    private String name;
    public Pet setName(String name) { this.name = name; return this; }        
}

class Cat extends Pet
{
    public Cat catchMice() { 
        System.out.println("I caught a mouse!"); 
        return this; 
    }
}

class Dog extends Pet
{
    public Dog catchFrisbee() { 
        System.out.println("I caught a frisbee!"); 
        return this; 
    }
}

class Bird extends Pet
{
    public Bird layEgg() {
        ...
        return this;
    }
}


{
    Cat c = new Cat();
    c.setName("Morris").catchMice(); // error! setName returns Pet, not Cat
    Dog d = new Dog();
    d.setName("Snoopy").catchFrisbee(); // error! setName returns Pet, not Dog
    Bird b = new Bird();
    b.setName("Tweety").layEgg(); // error! setName returns Pet, not Bird
}

在这种类层次结构中,有没有办法以不(有效)向上转换对象类型的方式返回 this

【问题讨论】:

  • 现在我明白为什么这么多人讨厌 Java。

标签: java inheritance method-chaining


【解决方案1】:

如果您想避免编译器发出未经检查的强制转换警告(并且不想@SuppressWarnings("unchecked")),那么您需要做更多的事情:

首先,您对 Pet 的定义必须是自引用的,因为 Pet 始终是泛型类型:

abstract class Pet <T extends Pet<T>>

其次,setName 中的(T) this 也未选中。为避免这种情况,请使用优秀的Generics FAQ by Angelika Langer 中的“getThis”技术:

“getThis”技巧提供了一种方法 恢复 this 的确切类型 参考。

这会产生下面的代码,该代码编译并运行时不会出现警告。如果您想扩展您的子类,那么该技术仍然适用(尽管您可能需要泛化您的中间类)。

生成的代码是:

public class TestClass {

  static abstract class Pet <T extends Pet<T>> {
    private String name;

    protected abstract T getThis();

    public T setName(String name) {
      this.name = name;
      return getThis(); }  
  }

  static class Cat extends Pet<Cat> {
    @Override protected Cat getThis() { return this; }

    public Cat catchMice() {
      System.out.println("I caught a mouse!");
      return getThis();
    }
  }

  static class Dog extends Pet<Dog> {
    @Override protected Dog getThis() { return this; }

    public Dog catchFrisbee() {
      System.out.println("I caught a frisbee!");
      return getThis();
    }
  }

  public static void main(String[] args) {
    Cat c = new Cat();
    c.setName("Morris").catchMice();
    Dog d = new Dog();
    d.setName("Snoopy").catchFrisbee();
  }
}

【讨论】:

  • 这样代码变得更干净了,我会花一些时间阅读完整的 Angelika 文章,谢谢 vm!
  • class Snake extends Pet&lt;Cat&gt; {@Override protected Cat getThis() {return new Cat();}}
  • 这有点棘手,但是当你有非抽象的、非最终的类在中间并且需要创建一个实例时。例如,假设您有一个static class Poodle extends Dog&lt;Poodle&gt;,并将Dog 更改为static class Dog&lt;T extends Dog&lt;T&gt;&gt; extends Pet&lt;T&gt;。现在创建Dog 的原始实例会很困难。
  • 有什么方法可以与匿名类一起工作吗?我找不到一种方法让它为泛型 T 自我引用:/
  • 我创建了一个有用的东西:class PetAnnon extends Pet&lt;PetAnnon&gt;{},在每个匿名类上我都像 new Pet&lt;PetAnnon&gt;{... 一样使用它,现在像 &lt;T&gt; T get(Class&lt;T&gt; cl){return (T)this.val;} 这样的方法将再次起作用。
【解决方案2】:

这个老把戏怎么样:

abstract class Pet<T extends Pet>
{
    private String name;
    public T setName(String name) { this.name = name; return (T) this; }        
}

class Cat extends Pet<Cat>
{
    /* ... */
}

class Dog extends Pet<Dog>
{
    /* ... */
}

【讨论】:

  • +1,比我表达的更简洁。但是考虑到 java 泛型已经存在了多久,它可能是一个多么古老的技巧?
  • 啊哈,我想会有一些与泛型有关的东西,只是不知道是什么。谢谢!
  • @Steve B:它在Java中并不老掉牙(实际上,我认为我没有看到它在Java中使用过),但它在C++中已经使用了很长时间了。
  • 嗯。您能否也添加一个向上转换和向下转换的示例?例如宠物> 宠物 = c; ((猫)宠物).catchMice(); (我有这个权利吗?)
【解决方案3】:

不,不是真的。您可以通过使用协变返回类型来解决它(感谢 McDowell 的正确名称):

@Override
public Cat setName(String name) {
    super.setName(name);
    return this;
}

(协变返回类型仅适用于 Java 5 及更高版本,如果您担心的话。)

【讨论】:

    【解决方案4】:

    这有点令人费解,但您可以使用泛型来做到这一点:

    abstract class Pet< T extends Pet > {
        private String name;
    
        public T setName( String name ) {
            this.name = name;
            return (T)this;
        }
    
        public static class Cat extends Pet< Cat > {
            public Cat catchMice() {
                System.out.println( "I caught a mouse!" );
                return this;
            }
        }
    
        public static class Dog extends Pet< Dog > {
            public Dog catchFrisbee() {
                System.out.println( "I caught a frisbee!" );
                return this;
            }
        }
    
        public static void main (String[] args){
            Cat c = new Cat();
            c.setName( "Morris" ).catchMice(); // error! setName returns Pet, not Cat
            Dog d = new Dog();
            d.setName( "Snoopy" ).catchFrisbee(); // error! setName returns Pet, not Dog
        }
    
    }
    

    【讨论】:

      【解决方案5】:
      public class Pet<AnimalType extends Pet> {
      
      private String name;
          public AnimalType setName(String name) {
             this.name = name; return (AnimalType)this; 
          }        
      }
      

      public class Cat extends Pet<Cat> {
      
          public Cat catchMice() {return this;}
      
          public static void main(String[] args) {
              Cat c = new Cat().setName("bob").catchMice();
          }
      

      }

      【讨论】:

      • @Steve B. - +1,跟我打赌!
      • 编辑:复制/粘贴您的代码就可以了。我意识到我的基类是X extends Y 而不是X extends Y&lt;X&gt;。解决了!
      猜你喜欢
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多