Julio_Av Julio_Av - 7 months ago 31
Java Question

Java: Fill a dynamic list from a generic class

I have a class:

public class Car {
public int year;
public String model;

and a list:

List<Car> list = new DB<>(new Car()).getList();

I need to fill that list from my class Car to fill for example an json array or a table from a sqlite db.

Below I have my generic class that it suppose to fill it:

public class DB<T>{
private T type;
public DB(T type){this.type = type;}

public List<T> getList(){
List<T> list = new ArrayList<>();
for(int i=0; i<2; i++){
T object = (T)type.getClass().newInstance();// this line doesn't work
return list;

My problem lies when I try to make a new instance of 'T' to add a new and different object in my list.

I tried doing something like this:

T object = new T();

But returns a empty object, so I tried doing a cast (the one that I did in my generic class) and my console gave me this error:

java.lang.InstantiationException: can't instantiate class
com.example.myprojects.Car; no empty constructor

I don't know if I'm missing something, so my question is why this doesn't let me create a new instance or if there's another workaround that would help me create a new instance?

Edit: Following Nicola's Answer I rewritten my generic class like this:

public class DB<T>{
private Class<T> type;
public DB(Class<T> type){this.type = type;}

public List<T> getList() throws IllegalAccessException, InstantiationException {
List<T> a = new ArrayList<>();
a.add(type.newInstance());// Still can't instance
}cath(Exeption e){e.printStackTrace(); }
return a;

But my console continues to show the same mistake , even declared an empty constructor in my class


Have you tried to declare your inner classes as static?

public static class Car {
    public int year;
    public String model;