Create instance of generic type in Java?

后端 未结 27 3814
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 06:14

Is it possible to create an instance of a generic type in Java? I\'m thinking based on what I\'ve seen that the answer is no (due to type erasure), but

27条回答
  •  天命终不由人
    2020-11-21 06:43

    If you need a new instance of a type argument inside a generic class then make your constructors demand its class...

    public final class Foo {
    
        private Class typeArgumentClass;
    
        public Foo(Class typeArgumentClass) {
    
            this.typeArgumentClass = typeArgumentClass;
        }
    
        public void doSomethingThatRequiresNewT() throws Exception {
    
            T myNewT = typeArgumentClass.newInstance();
            ...
        }
    }
    

    Usage:

    Foo barFoo = new Foo(Bar.class);
    Foo etcFoo = new Foo(Etc.class);
    

    Pros:

    • Much simpler (and less problematic) than Robertson's Super Type Token (STT) approach.
    • Much more efficient than the STT approach (which will eat your cellphone for breakfast).

    Cons:

    • Can't pass Class to a default constructor (which is why Foo is final). If you really do need a default constructor you can always add a setter method but then you must remember to give her a call later.
    • Robertson's objection... More Bars than a black sheep (although specifying the type argument class one more time won't exactly kill you). And contrary to Robertson's claims this does not violate the DRY principal anyway because the compiler will ensure type correctness.
    • Not entirely Fooproof. For starters... newInstance() will throw a wobbler if the type argument class does not have a default constructor. This does apply to all known solutions though anyway.
    • Lacks the total encapsulation of the STT approach. Not a big deal though (considering the outrageous performance overhead of STT).

提交回复
热议问题