lundi 12 décembre 2016

How to set data into Generics class?

I want to read data from my database and set them into my classes which are different, such as student.class, staff.class and so on. After set the data, they will be put into a ArrayList. Each class has their own get and set methods for each field. I want to use reflection as a solution, but I don't know how to type the code. Can anyone give my some advice?

Here is my code:

 public ArrayList<E> selectFromDatabase(String tableName, HashMap<String, String> condition) {
    ArrayList<E> list = new ArrayList<>();
    ResultSet rs = null;
    String sql = getSql(SELECT, tableName, null, condition);
    try {
        rs = executeSql(sql);
        while (rs.next()) {
            E e = new E();
            Class<?> aClass = e.getClass();
            Method[] methods = aClass.getMethods();
            for (Method m:methods) {
                //How to set data to into the generics class?
            }
            list.add(e);
        }
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }

    return list;
}

Thank you in advance.





Aucun commentaire:

Enregistrer un commentaire