有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

lambda使用java匿名函数返回值

从C#转换到Java,并试图清除一些代码中的大量连接泄漏

为了防止泄漏,我会做如下的事情

public class DB{
    public interface StatementUser{
         public void useit(Statement cmd);
    }

    public static void UseCommand(StatementUser usingfunc){
        try(Connection cnn = new Connection(...)){
            cnn.open();
            try(Statement stmt = new Statement(cnn)){
                usingfunc(stmt);
            }
        }
    }

    static void main(string[] args){
        int affected = 0;
        DB.useStatement((stmt) -> {
            // THIS STATEMENT IS DISALLOWED
            affected = ... select/update... whatever
        });
        System.out.println("Records: " + affected);
    }
}

我喜欢这个委托,因为它处理清理工作,但仍然将与数据的大部分交互留给了开发人员的创造力

我发现对affected的赋值被认为是访问其作用域之外的变量,这是不允许的。所以现在我有点不知所措,不知道如何在Java中执行类似的操作(我想保持connection/statement对象的通用用法)

我想到的每一件事都让事情变得更加丑陋,所以我怀疑我只是在走一条完全没有出路的道路

Java做这种事情的方式是什么?(我知道这可能与我预期的大不相同)


共 (1) 个答案

  1. # 1 楼答案

    编写此代码的另一种方法如下:

    package controllers;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class DB {
    
        public interface StatementUser<T> {
            T run(Statement cmd);
        }
    
        public static <T> T runStatement(StatementUser<T> usingfunc) {
            try(Connection cnn = getConnection()){
                try(Statement stmt = cnn.createStatement()){
                    return usingfunc.run(stmt);
                }
            } catch(SQLException ex) {
                throw new RuntimeException(ex);
            }
        }
    
        private static Connection getConnection() throws SQLException {
            return ...; // someway to acquire a connection
        }
    
        public static void main(String[] args) {
            int affected = DB.runStatement(cmd -> {
                // do something with the statement
                return 10;
            });
            System.out.println(affected);
        }
    }