[英]using java anonymous functions to return values
Transitioning from C# to Java and attempting to clean up a bunch of Connection leaks in some code. 从C#过渡到Java,并尝试清除一些代码中的许多Connection泄漏。
To prevent leaks in I would have done something like 为了防止泄漏,我会做类似的事情
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);
}
}
I like this delegate because it handles the cleanup but still leaves most of the interaction with the data to the developer's creativity. 我喜欢这个委托,因为它负责清理,但仍将大部分与数据的交互留给开发人员来创造。
I get that the assignment to affected
is considered accessing a variable outside of its scope, and not allowed. 我知道,分配给affected
被认为是在其范围之外访问变量,并且不允许这样做。 So now I'm kind of at a loss as to how to perform a similar operation in Java (I want to maintain the generic usage of the connection/statement object) 所以现在我有点不知如何在Java中执行类似的操作(我想保持连接/声明对象的通用用法)
Everything I've come up with just makes it uglier, so I suspect I'm simply heading down a completely dead-end path. 我想出的一切都变得很丑陋,所以我怀疑我只是在走一条完全死路。
What is a Java way of doing something like this? Java做这种事情的方式是什么? (I get that this may look drastically different than I'm expecting) (我知道这看起来可能与我预期的完全不同)
Another way to write this code is like this: 编写此代码的另一种方式是这样的:
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.