I am new to java generics and I need to instantiate a new instance of a T
object my <T extends Foo>
. But I am having trouble finding a way to do that. How can I create a new instance of an object T
.
Here is how my method look like
Class Bar extends Foo{
public Bar(){}
@Override
doThings(){}
}
class Foo {
public Foo(){}
doThings(){}
}
private <T extends Foo> List<T> doSommething(Somedata data, List<T> foos) {
T t = new T();//I need to instantiate a T object that works for foo and bar
foos.add(t);//t here could be foo, or bar
return foos;
}
I have tried:
T t = new T(); wrong
T t = (T)(new Foo()); that gives me a foo obj, but I need a T object that extends Foo;
T t;
t.doSomething(); //that asks me to assign a value to t
t = null
t.doSomething(); //null exception
I expect to create an instance of an object T
that works for Foo
and Bar