繁体   English   中英

使用Java匿名函数返回值

[英]using java anonymous functions to return values

从C#过渡到Java,并尝试清除一些代码中的许多Connection泄漏。

为了防止泄漏,我会做类似的事情

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中执行类似的操作(我想保持连接/声明对象的通用用法)

我想出的一切都变得很丑陋,所以我怀疑我只是在走一条完全死路。

Java做这种事情的方式是什么? (我知道这看起来可能与我预期的完全不同)

编写此代码的另一种方式是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM