1

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

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • You literally can't do this, certainly not without passing a `Supplier`. – Louis Wasserman Nov 16 '22 at 19:45
  • I recommend reading about type erasure, e.g. in [this article at `docs.oracle.com`](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). – Turing85 Nov 16 '22 at 19:48
  • Does this answer your question? [Java generics type erasure: when and what happens?](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – Turing85 Nov 16 '22 at 19:49
  • You sort-of can do this (with `Class`/`Constructor`/reflection in general), but it's very brittle, slow, and verbose. A counter-question: _why_ do you want this? For what purpose does it serve (beyond just "being used in your method", _what_ is that method truly for?). – Rogue Nov 16 '22 at 19:50
  • @Rogue: even with reflection, you can't necessarily do it without passing the `Class` object or the like. (You could do it _if_ the list is nonempty and _if_ the elements of the list are all going to be the same concrete type.) – Louis Wasserman Nov 16 '22 at 19:57
  • 1
    @LouisWasserman hence `Class`. That said, the whole question smells of an [XY Problem](https://xyproblem.info/). – Rogue Nov 16 '22 at 19:58
  • Does this answer your question? [Why can't you create an instance of a generic type using "new" operator?](https://stackoverflow.com/questions/30646486/why-cant-you-create-an-instance-of-a-generic-type-using-new-operator) – Savior Nov 16 '22 at 20:33
  • I am still not sure how to pass a Class to my new instance. Class type; type = null;//I have tried to initiate it with many values, but I don't seem to get it right. T foo= newInstance(type); public T newInstance(Class cls) throws InstantiationException, IllegalAccessException { T myObject = cls.newInstance(); return myObject; } – Celso Henrique Nov 17 '22 at 17:52

0 Answers0