看这段代码:
IDfSessionManager manager = DfcSessionManager.getSessionManager();
try {
IDfSession session = manager.getSession(DfsUtils.getCurrentRepository());
...
return somewhat; //May be without return statement
} finally {
if (session != null) {
manager.release(session);
}
}
这样的构造重复多次并围绕不同的代码。这可以是带有或不带有 return 语句的方法。 我想使这个 try-finally block 可以重用。
我想到了这样的认识。
public abstract class ISafeExecute<T> {
private IDfSession session = null;
protected abstract T execute() throws DfException;
public T executeSafely() throws Exception {
IDfSessionManager manager = DfcSessionManager.getSessionManager();
try {
session = manager.getSession(DfsUtils.getCurrentRepository());
return execute();
} finally {
if (session != null) {
manager.release(session);
}
}
}
public IDfSession getSession() {
return session;
}
session 字段是用 public getter 创建的。
我们可以像这样使用这个类(返回对象):
return new ISafeExecute<String>() {
@Override
public String execute() throws DfException {
return getSession().getLoginTicket();
}
}.executeSafely();
或者没有返回对象:
new ISafeExecute() {
@Override
public Object execute() {
someMethod();
return null;
}
}.executeSafely();
最佳答案
您可以使用 Runnable<T>
建立一个机制来做到这一点(有点像将一个函数注入(inject)另一个函数):
public void runInSession(Runnable<IDfSession> runnable) {
IDfSession session = null;
try {
session = manager.getSession(DfsUtils.getCurrentRepository());
runnable.run(session);
} finally {
if (session != null) {
manager.release(session);
}
}
}
您还可以使用更多泛型来返回值。我这里缺少 Java 编译器,但我对语法有点不确定。
编辑,如我所见:
使用自定义 ISafeExecute
界面可能比使用 Runnable<T>
更整洁,但想法保持不变。您可以构建它,以便可以优雅地放置返回值(或错误):
interface ISafeExecute<T> {
void execute(IDfSession session);
T getResult();
Exception getException();
}
mySafeExecute.execute(session);
if(mySafeExecute.getException() == null) {
return mySafeExecute.getResult();
} else {
// runtime exception or declaration in method
// signature
throw new RuntimeException(mySafeExecute.getException());
}
关于 java 。重用带有返回的 try-finally 构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969619/