2 回答
TA贡献1852条经验 获得超1个赞
您可以创建工厂方法来创建Autocloseable包装器。
public Autocloseable autocloseable(Result result) {
return new Autocloseable() {
public void close() {
result.content.close();
}
}
}
然后像这样使用 try-with-resources
Result result = getResult();
try (Autocloseable ac = autocloseable(result)) {
doStuffWith(result);
}
或者,当然,过度设计
class AutoclosingWrapper<T> implements Autocloseable {
private T object;
private Function<T, Autocloseable> autocloseable;
public AutoclosingWrapper(Supplier<T> c, Function<T, Autocloseable> a) {
this(c.get(), a);
}
public AutoclosingWrapper(T t, Function<T, Autocloseable> a) {
object = t;
autocloseable = a;
}
public T getObject() {
return object;
}
public void close() {
autocloseable.apply(object).close();
}
}
这被称为
try (AutoclosingWrapper<Result> wrapper = new AutoclosingWrapper(this::getResult, r -> r.content)) {
doStuffWith(wrapper.getObject());
}
TA贡献1757条经验 获得超7个赞
也许不是很好,但很明显:
Result result = getResult();
try (InputStream content = result.content) {
...
}
可以变成
Result result;
try (InputStream content = (result = getResult()).content) {
...
}
添加回答
举报