Storing different parameterized types in the same shared array in Java

I like to create a view of database table classes in java. A column is designed as a general class so that it can handle all the different types of data columns that may be available.

public class TableColumn<T> { ... } 

The table has 0 ... n TableColumns, so my table class looks like this:

 public class Table { protected ArrayList<TableColumn<T>> columns = new ArrayList<TableColumn<T>>(); ... } 

The idea is to add columns as follows.

 Table t = new Table(); t.addColumn(String.class); t.addColumn(Integer.class); t.addColumn(Date.class); t.addColumn(String.class); 

And then I can manipulate the data as follows:

 String a = t.Cols(2).Row(3); t.Col(2).Row(3) = "b"; 

But I'm losing the safty type with my current way of achieving this ... My problem is how to implement columns due to the different data types that the potential of the columns can get.

Does anyone have a clue?

+4
source share
2 answers

If there are a limited number of type combinations, you can use interfaces for these combinations. This will allow you to be able to store the column in the same way, and you will not need special casting.

 t.addColumn(MyInterface.class); 

Another method, which would still not be as clean as what you want, but is kind of inevitable, is to use a new class that allows you to take on the burden of some type checking and type checking.

Example:

 public static class MyWrapper{ Class<?>[] validPossibleClasses; Object o; public MyWrapper(Class<?> ...classes){ this.validPossibleClasses = classes; } public boolean validateClass(Class<?> clazz){ for (Class<?> c : validPossibleClasses){ if (!c.isAssignableFrom(clazz)) return false; } return true; } public void set(Object o) throws Exception{ if (!validateClass(o.getClass())) throw new Exception("Bad Cast"); this.o = o; } public String getString(){ return (String) o; } public Integer getInt(){ return (Integer) o; } ... // more specific getters } 

Usage will be that way

 String a = t.Cols(2).Row(3).getString(); t.Col(2).Row(3).set("b"); 
0
source

Why not just create a different object for each table? Sort of:

Class Players with fields:

 String name; int points; int number; 

Class stadium with fields:

 String location; Date dateBuilt; 

Class command with fields:

 String name; ArrayList<Players> roster; 

Then you can simply hold all the values ​​in a list or arraylist and separate them by the database tables and not guess which table you are in. You will have to hold more objects, but you would be able to learn more about what you are dealing with.

0
source

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


All Articles