简体   繁体   English

Java 不支持枚举上的协变返回类型吗?

[英]Does Java not support Covariant Return Types on Enums?

I am trying to implement a factory pattern where users can choose from a defined set of options.我正在尝试实现一种工厂模式,用户可以在其中从一组定义的选项中进行选择。 To make it easy to store in the database I made the options an enum.为了便于存储在数据库中,我将选项设置为枚举。 Now in one case I need to get the specific implementation back.现在在一种情况下,我需要恢复特定的实现。 I was hoping to avoid explicitly instantiating the specific implementation because my factory caches some of the shared dependencies of the things it creates.我希望避免显式实例化特定的实现,因为我的工厂缓存了它创建的东西的一些共享依赖项。 I assumed I could use covariant return types to accomplish this but it appears they do not work with enums.我以为我可以使用协变返回类型来完成此操作,但似乎它们不适用于枚举。 I'm assuming it is related to how enums can't leverage generic types (which would also solve my problem.) So, does Java not support covariant return types on methods in enums?我假设它与枚举如何不能利用泛型类型有关(这也可以解决我的问题。)那么,Java 是否不支持枚举中方法的协变返回类型?

public class Scratch
{
   public static class Door  {      }    
   public static class ExteriorDoor extends Door  {  }  
   public interface IDoorFactory  
   {    
      public Door getDoor();
   }

   public enum DoorFactory implements IDoorFactory
   {
       EXTERIOR
       {
          @Override
          public ExteriorDoor getDoor()
          {
             //valid covariant method override
             return new ExteriorDoor(); 
          }
       },
       INTERIOR
       {
          @Override
          public Door getDoor()
          {
            return new Door();
          }
        }
    }  

   public static void main(String[] args)  
   {
    //invalid, method only returns a Door
    ExteriorDoor door = DoorFactory.EXTERIOR.getDoor();  
   }
}

Enum constants are fields, not types.枚举常量是字段,而不是类型。 The return type is covariant, but the types of the enumerated constants are anonymous classes.返回类型是协变的,但枚举常量的类型是匿名类。 For this reason, the most specific static type for the value returned by getDoor() in your example will be that of Door .因此,您的示例中getDoor()返回的值最具体的 static 类型将是Door的类型。

EXTERIOR has type DoorFactory implements IDoorFactory . EXTERIOR具有类型DoorFactory implements IDoorFactory Hence DoorFactory.EXTERIOR.getDoor() has type Door , not type ExteriorDoor .因此DoorFactory.EXTERIOR.getDoor()具有类型Door ,而不是类型ExteriorDoor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM