mercredi 14 juillet 2021

Make a List from generic method accept Class

So i want to build a framework similar to SpringBootJPA (just for fun)

The code works fine on getting the data from the database but now i need to assign to my List the obtained data as T , the compiler doesn't allow me to do that so i need a different solution

also is the any way the Serializable interface can help me here?

thanks in advance

 //Code

 <T> List<T> getAll(Class<T> modelClass) {

    String sql = "SELECT * FROM "+modelClass.getSimpleName();

    try {

        Statement statement = Objects.requireNonNull(getConnection()).createStatement();

        ResultSet resultSet = statement.executeQuery(sql);

        List<> list = new ArrayList<>(); 



        while (resultSet.next()){

            String[] Data = new String[modelClass.getDeclaredFields().length];

            for (int i = 0; i < Data.length; i++) {

                Data[i] = getSQL_AsString(resultSet,modelClass.getDeclaredFields()[i].getType(),i+1);

            }

            list.add(); //I want this to be list.add(new modelClass(Data))

        }

        return list;

    }catch (SQLException | InstantiationException | IllegalAccessException e){e.printStackTrace();}

    return null;
}




Aucun commentaire:

Enregistrer un commentaire