Avoiding Returning Wildcard Types

后端 未结 4 1566
暗喜
暗喜 2021-02-08 10:26

I have a class with a collection of Wildcard Types that is a singleton, something like:

public ObliviousClass{

    private static final ObliviousClass INSTANCE          


        
4条回答
  •  太阳男子
    2021-02-08 10:51

    For those landing on this question these many years later, this is not how Java generics are designed to be used. (I was going to comment but had more to details.)

    The generic pattern manages a single parent class per type ID rather than multiple different classes. If we consider the simpler List, a list of strings OR integers (as List or List) is how generics are defined. One class per type. This way, there is a consistent type when the values are referenced. Storing unrelated types would be the same as List. Only the programmer can know when multiple types are stored and how to retrieve them with casting.

    It would be ok to store subclasses to a parent class, but when accessed from the collection without casting, the parent class contact is all that is known. For instance, a generic collection defined with an interface like Map. However, only the run() method is visible even if other public methods are added to implementations (unless the programmer explicitly casts). To access additional methods, casting is necessary.

    This is a limitation in Java. A language could be defined to know the L-Value type - even Java. But it wasn't. When new features are added, there are many backward compatible considerations [Sun and] Oracle take into account. Code compiled with generics was designed to run on older JVMs with type erasure. Java uses type erasure at compile time once it has determined that the generics are consistently reference. The bytecode uses Object as if the instance was (sort of) defined as List. If the choice was made to abandon backward compatibility, like Java 9 and 11, then multiple types might have been workable.

    提交回复
    热议问题