【问题标题】:Java: return List of objects of the type that calls the methodJava:返回调用方法的类型的对象列表
【发布时间】:2017-03-14 03:22:57
【问题描述】:

我要做的是返回调用该方法的任何类型的对象的 java 列表。

List<Playlist> playlist = Table.selectAll();

这些 java 对象(在本例中为 Playlist)应该每个都包含我的 SQL ResultSet 中的一行值。

public class Table extends Database {

    public List<this> selectAll() {
        List<this> newList = new List<this>();

        String tableName = this.getClass().getSimpleName().toLowerCase();
        Field[] fields = this.getClass().getDeclaredFields();

        Connection connection = getConnection();
        PreparedStatement preStat = null;
        ResultSet resultSet = null;

        try {
            preStat = connection.prepareStatement("SELECT * FROM " + tableName);
            resultSet = getFromDB(preStat);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // create a list of Objects of class ‘this’ (in this case Playlist) 
        // and using the fields obtained from .getDeclaredFields() 
        // assign values to each Object from the ‘preStat’ results 
        // then put those objects into ‘newList’

        return newList;
    }

}

我在这里做错了什么?我应该将 List 传递给方法而不是返回返回,但是我将如何从每个 ResultSet 创建一个对象,使用 .getDeclaredFields() 为其分配值,然后将对象分配给 List?

【问题讨论】:

  • 你的表名是Table?这是一个糟糕的表名选择!

标签: java jdbc reflection


【解决方案1】:
List<this> newList = new List<this>();

不行,一定是的

List<PlayList> newList = new List<>();

然后在你的 cmets 中做

while (resultSet.next()) {
    PlayList l = new PlayList();
    l.setId(resultSet.getInt(1));
    l.setYourStringField(resultSet.getString(2));
    l.setAnotherStringField(resultSet.getString(3));
    newList.add(l);
}

resultSet.close();
preStat.close();
connection.close();

成为 PlayList 对象的 setIdsetYourStringFieldsetAnotherStringField 属性设置器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2021-12-15
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多