Non-generic reference to generic class results in non-generic return types

后端 未结 3 652
闹比i
闹比i 2021-01-02 13:31

I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

public class Thing {
    public Collection<         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 13:50

    I think this is totally normal. In my opinion using Thing t = new Thing(); for generic enabled class is totally a mistake. When compiler see a generic class used as a class without type parameter, it think it must erase all generic types from that class. This is how you can compile old codes without use of generics in new java compilers and compiler let that old codes use generic enabled classes (e.g. java.util.ArrayList) without any problem. (and this is how java not need separated System.Collection.Generic.List and System.Collection.List like C#). You can run Thing t = new Thing(); with adding a simple type parameter on it, Thing t = new Thing();, only thing java compiler needs is making sure that you are using java generic consciously. I never can blame Java for its great backward compatibility.

    I know I am a bit late :D

    提交回复
    热议问题