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

标签 java inheritance design-patterns overriding

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

所以我做了下面的代码,尝试类似于命令模式的东西似乎工作得很好。它仅接收字符串中的 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});

最佳答案

I can't think any way of doing it without making an abstract method and class.

抽象类正是您需要的机制

I should make another class to be able to instantiate, which can't be abstract as well.

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

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;
    };
}

关于Java - 如何在子匿名类中强制重写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805937/

相关文章:

java - 如何在Spring MVC中将多维数组处理为@RequestParam?

java - JPanel 中的组件自动消失

java - MySQL 数据库无法连接到 Android 应用程序

c++ - 我如何在 C++ 中找到哪个子类正在调用父类的函数?

java - 如何生成需求,使用单例进行数据库连接的优缺点?

c# - 从泛型方法返回对象作为接口(interface)

java - WLS 10 客户端中抛出类未找到异常 (org.apache.openjpa.enhance.PersistenceCapable)

class - 为什么一个类可以实现多个接口(interface)?

Java,接口(interface)可以继承吗?

java - "Creator"配置继承对象的模式