请将其转换为通用形式

时间:2016-11-18 07:26:14

标签: java generics

我写了下面的函数,我想把它写成所有java bean的泛型函数,它将返回我传递的bean名称类型列表。

public List<_ItemCreditQuality> getCrediQuality(String type,String def) throws SQLException{

        sql = "";

        stmt = con.createStatement();

        rs = stmt.executeQuery(sql);

        QueryRunner run = new QueryRunner();
        ResultSetHandler<List<_ItemCreditQuality>> h = new BeanListHandler<_ItemCreditQuality>(_ItemCreditQuality.class);
        creditQualityList = run.query(con, sql, h);

        return creditQualityList;
    }

请帮忙。

1 个答案:

答案 0 :(得分:1)

做一些假设,这是一个例子:

public <T> List<T> getCreditQuality(Class<T> beanClass) throws SQLException {
    String sql = "SELECT * FROM " + beanClass.getSimpleName();
    try (
        Statement stmt = this.con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
    ) {
        QueryRunner run = new QueryRunner();
        ResultSetHandler<List<T>> h = new BeanListHandler<T>(beanClass);
        List<T> creditQualityList = run.query(this.con, sql, h);
        return creditQualityList;
    }
}

T可以是_ItemCreditQuality bean类,您可以这样称呼它:

List<_ItemCreditQuality> list = getCreditQuality(_ItemCreditQuality.class);