Why should I care that Java doesn't have reified generics?

后端 未结 13 756
予麋鹿
予麋鹿 2020-11-28 02:59

This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It\'s commonly-identified as a pain that Jav

13条回答
  •  时光取名叫无心
    2020-11-28 03:18

    From the few times that I came across this "need", it ultimately boils down to this construct:

    public class Foo {
    
        private T t;
    
        public Foo() {
            this.t = new T(); // Help?
        }
    
    }
    

    This does work in C# assuming that T has a default constructor. You can even get the runtime type by typeof(T) and get the constructors by Type.GetConstructor().

    The common Java solution would be to pass the Class as argument.

    public class Foo {
    
        private T t;
    
        public Foo(Class cls) throws Exception {
            this.t = cls.newInstance();
        }
    
    }
    

    (it does not necessarily need to be passed as constructor argument, as a method argument is also fine, the above is just an example, also the try-catch is omitted for brevity)

    For all other generic type constructs, the actual type can easily be resolved with a bit help of reflection. The below Q&A illustrate the use cases and possibilities:

    • Get generic type of java.util.List
    • How to get the generic type at runtime?
    • Get actual type of generic type argument on abstract superclass

提交回复
热议问题