java - 在函数中使用泛型的问题

标签 java generics

我有这个功能,需要把它变成一个功能。唯一的区别是输入变量 sourceColumnValue 的类型。此变量可以是 StringInteger 但函数的返回值必须始终是 Integer。 我知道我需要使用泛型但做不到。

    public Integer selectReturnInt(String tableName, String sourceColumnName, String sourceColumnValue, String targetColumnName) {
    Integer returned = null;
    String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";

    try {
        Connection connection = ConnectionManager.getInstance().open();
        java.sql.Statement statement = connection.createStatement();
        statement.execute(query.toString());
        ResultSet rs = statement.getResultSet();
        while(rs.next()){
            returned = rs.getInt(targetColumnName);
        }

        rs.close();
        statement.close();
        ConnectionManager.getInstance().close(connection);
    } catch (SQLException e) {
        System.out.println("Заявката не може да бъде изпълнена!");
        System.out.println(e);
    }

    return returned;
}


// SELECT (RETURN INTEGER)
public Integer selectIntReturnInt(String tableName, String sourceColumnName, Integer sourceColumnValue, String targetColumnName) {
    Integer returned = null;
    String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";

    try {
        Connection connection = ConnectionManager.getInstance().open();
        java.sql.Statement statement = connection.createStatement();
        statement.execute(query.toString());
        ResultSet rs = statement.getResultSet();
        while(rs.next()){
            returned = rs.getInt(targetColumnName);
        }

        rs.close();
        statement.close();
        ConnectionManager.getInstance().close(connection);
    } catch (SQLException e) {
        System.out.println("Заявката не може да бъде изпълнена!");
        System.out.println(e);
    }

    return returned;
}

最佳答案

您不需要为此使用泛型。当您支持的类型可能很多并且您事先不知道它们并且它们共享一些共同点时,应该使用泛型在他们中。

仅针对两种类型泛型不是一个好的选择。使用 objects 可能是更好的选择。

也许我会说您甚至不需要合并这些函数,这就是多态性的用途。保持谨慎将使代码更具可读性

关于java - 在函数中使用泛型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5133958/

相关文章:

java - 在 Kotlin 中 gradle distTar 后无法从 src/main/resources 读取文件

c++ - 通用回调

generics - Swift 泛型函数(n 选 k)

java - 使 ImageView 在设定的时间内可见

java - 在迭代 ConcurrentHashMap 时添加和删除值

Java 虚拟机内部结构

java - 将对象数据从 JSP 传递到 Spring Controller Post 方法而不是 GET 方法

java - 从Java中的泛型方法获取子类

generics - 从通用类型获取 Moshi 适配器 - Kotlin

java - 强制 child 使用自己定义的枚举