Java-如何使子匿名类中的强制方法重写?

拉屎

我一直在设计一些源代码,因为在我们的项目中,进行SQL查询时会重复很多代码。

所以我在下面做了这段代码,尝试类似于Command模式的代码似乎可以正常工作。它仅接收字符串中的SQL查询和要在语句中设置的一些参数(如果需要)。因此,您可以将此代码用作匿名类,并仅定义对查询输出的处理方式来执行查询。

我的问题是我想设计该方法,使其必须在匿名子类中定义和编写方法getResult,但是如果没有抽象方法和类,我想不出任何方法。

如果QueryCommand变为抽象,则应使另一个类能够实例化,该类也不能抽象。还有其他方法可以强制儿童班压倒一切吗?我正在寻找最聪明,最简单的方法来实现它。

不知道如何搜索相似的模式或解决方案。

提前致谢。

源代码:

import java.sql.Connection;
import java.sql.SQLException;

public interface IQueryCommand<T> {
    T executeQuery(Connection conn, String query, Object... args) throws SQLException;
}


import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import org.apache.log4j.Logger;

public class QueryCommand<T> implements IQueryCommand<T> {
    private Logger LOGGER = Logger.getLogger(this.getClass());

    /** The constant ERROR_CLOSING_RESULT_SET */
    protected static final String ERROR_CLOSING_RESULT_SET = "Error when closing ResultSet";

    /** The Constant ERROR_CLOSING_PREPARED_STATEMENT. */
    protected static final String ERROR_CLOSING_PREPARED_STATEMENT = "Error when closing PreparedStatement";

    // FIXME: I want this method to be mandatory to be defined in the anonymous child class
    protected T getResult(ResultSet rs) throws SQLException {
        return null;
    };


    public T executeQuery(Connection conn, String sqlQuery, Object... args) throws SQLException {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(sqlQuery);
        }
        PreparedStatement ps = null;
        ps = conn.prepareStatement(sqlQuery);

        return executeQuery(conn, ps, args);
    }

    public T executeQuery(Connection conn, PreparedStatement ps, Object... args) throws SQLException {
        ResultSet rs = null;
        try {
            if(args != null && args.length > 0) {           
                for(int i=0; i< args.length; i++) {
                    setArg(ps, i+1, args[i]);
                }
            }
            rs = ps.executeQuery();
            T result = getResult(rs); // Method defined in child class

            return result;
        } catch (SQLException e) {
            throw e;
        } finally {     
            if(rs != null) {
                try {
                    rs.close();
                } catch (final SQLException e) {
                    LOGGER.error(ERROR_CLOSING_RESULT_SET, e);
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (final Exception e) {
                    if(ps instanceof CallableStatement) {
                        LOGGER.error("Error when closing CallableStatement", e);
                    } else if(ps instanceof PreparedStatement) {
                        LOGGER.error(ERROR_CLOSING_PREPARED_STATEMENT, e);
                    }
                }
            }
        }
    }


    /**
     * Sets a value on the PreparedStatemente with a method dependending on dataType
     * 
     * @param ps the preparedStatement
     * @param idx the index on which the value is set
     * @param value the value to set
     * @throws SQLException if an error is detected
     */
    private void setArg(PreparedStatement ps, int idx, Object value) throws SQLException {
        // Implementation not relevant...
    }
}

如何使用此示例

sqlQuery = " SELECT X FROM Y WHERE countryId = ? and languageId = ?";
return new QueryCommand<String>() {
    // This method should be REQUIRED when compiling
    @Override
    protected String getResult(ResultSet rs) throws SQLException {
        String result = "";
        while (rs.next()) {
            result = rs.getString("DESCRIPTION");
        }
        return result;
    };
}.executeQuery(getDB2Connection(), sqlQuery.toString(), new Object[] { countryIdParameter, languageIdParameter});
谢尔盖·卡里尼琴科(Sergey Kalinichenko)

如果没有抽象方法和类,我想不出任何办法。

抽象类正是您需要的机制

我应该使另一个类能够实例化,它也不能是抽象的。

这是不正确的:匿名类完全有能力继承一个抽象类,甚至扩展一个接口,当然,前提是它们实现了所有抽象方法:

public class AbstractQueryCommand<T> implements IQueryCommand<T> {
    abstract protected String getResult(ResultSet rs) throws SQLException;
    ...
}
return new AbstractQueryCommand<String>() {
    @Override
    protected String getResult(ResultSet rs) throws SQLException {
        String result = "";
        while (rs.next()) {
            result = rs.getString("DESCRIPTION");
        }
        return result;
    };
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章