Creating a virtual template in Java

The situation I'm trying to create is as follows:

I have a base class containing a static template method that gets a ResultSet populated with a query in the database and returns a list with the correct results.

I have some classes that stem from the above, which represents each table from the database, and they all have a constructor that gets a ResultSet and builds an object.

The code I wrote is:

 public class TableBase { public static <T extends TableBase> List<T> getResults(ResultSet p_Rs) throws SQLException, InstantiationException, IllegalAccessException { List<T> v_Table = new ArrayList<T>(); T v_TB = null; while(p_Rs.next()) v_Table.add(new T(p_Rs)); return v_Table; } } 

The error I received is: Cannot instantiate the type T

It is clear to me that the compiler must “know” that all child classes implement a constructor that receives the ResultSet variable, but I cannot create an “abstract constructor”.

Does anyone know how to solve this?

Thanks to everyone in advance.

+4
source share
3 answers

You cannot create typical types.

You can use either Factory

  public static <T extends TableBase> List<T> getResults (ResultSet p_Rs, Factory<T> factory) //Create instance using factory 

Or a class as a type.

 public static <T extends TableBase> List<T> getResults (ResultSet p_Rs, Class<T> type) //type.newInstance() 
+2
source

You cannot do this. You must say that the runtime is accurately printed.

Perhaps you can do this:

  • TableBase must have a default constructor.
  • TableBase must have a setResultSet method.

     public class TableBase { public static <T extends TableBase> List<T> getResults(ResultSet p_Rs, Class<T> clazz) throws SQLException, InstantiationException, IllegalAccessException { List<T> v_Table = new ArrayList<T>(); T v_TB = clazz.newInstance(); while (p_Rs.next()) v_TB.setResultSet(p_Rs); v_Table.add(v_TB); return v_Table; } } 
+1
source

You can use reflection, something like:

 while(p_Rs.next()) v_Table.add(newInstance(T, p_Rs)); public <T extends TableBase> T newInstance(T t, ResultSet p_Rs){ try { Constructor constructor = t.getClass().getDeclaredConstructor(ResultSet.class); return (T)constructor.newInstance(p_Rs); } catch (Exception e) { throw new RuntimeException(); } } 
0
source

Source: https://habr.com/ru/post/1436506/


All Articles