Question1 可能重复或 Question2 ,但对我来说还不清楚。 他们说,try-with-resources 仅受 19 api 支持,但请参阅 that question事实并非如此。
我自己用Realm
测试过。
boolean isClosed = RealmManager.isClosed(); //false here
try (Realm realm = RealmManager.getRealm()) {
realm.executeTransaction(r -> r.where(User.class).findAll());
} catch (Exception ex) {
ex.printStackTrace();
}
isClosed = RealmManager.isClosed(); //true here
public static boolean isClosed() {
return realm == null || realm.isClosed();
}
它在 22 api(真实手机)和 16 api(模拟器)上运行良好。 那么这个 block 在大多数手机上是否可以在 19 之前的 api 上正常工作,真相在哪里?
我使用 Retrolabmda
。
渐变配置:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
最佳答案
您可以使用 Android Studio 3.0 在所有 API 级别使用try-with-resources:
Android Studio 3.0 Preview 1 and later extends support for try-with-resources to all Android API levels.
此外,如果您为 API 级别 < 19 构建应用程序,则需要将注释 @SuppressLint("NewApi")
添加到代码块以隐藏警告。在这种情况下 annotation is not applicable ,但是您可以忽略警告,构建并运行您的应用程序,即使 try-with-resources 代码块被突出显示为错误也是如此。
关于java - Try-with-resources api pre 19,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45948628/