Search code examples
javagenericsjshell

Question about return type( need to return instances of different classes) in generics


So my current code looks like this. The idea is to take in an instance of different classes using generic type T and return those instances.

I should be able to call instances of classes like this

new A().add(new B())
    public static <T> T <T> add(T t) {
        return new T();
    }

Basically to me the return type should be the class itself so that it can take a new instance through the return type.

Can someone guide me as to where my logic is going wrong?


Solution

  • You can't call a constructor just from the generic type because 1. type erasure means T gets turned into Object (or whatever its upper bound is) at runtime, and 2. you don't know that the constructor necessarily takes 0 arguments.

    A better way to do it would be with a Supplier

    public static <T> T add(Supplier<T> supplier) {
        return supplier.get();
    }
    

    and you could use this method like this. With method references, it's pretty concise.

    B b = YourClass.add(B::new);