java - findFragmentByTag 中的 Null 检查与 Objects.requireNonNull

标签 java android nullpointerexception

由于我在 Android findFragmentByTag() 中进行了 null 检查,代码检查建议我添加 Objects.requireNonNull() 方法。当我应用此检查时,代码检查不再发出警告。那么哪一个更好呢?

我已经经历过这个 SO Question 。根据我的理解(我可能是错的), NullPointerException 无论如何都会被抛出。

           //3. Hide analytics fragment
            //if (fragmentManager.findFragmentByTag(TAG_ANALYTICS_FRAGMENT) != null) {
                ft.hide(Objects.requireNonNull(fragmentManager.findFragmentByTag(TAG_ANALYTICS_FRAGMENT)));
            //}
            //4. Hide settings fragment
            if (fragmentManager.findFragmentByTag(TAG_SETTINGS_FRAGMENT) != null) {
                ft.hide(fragmentManager.findFragmentByTag(TAG_SETTINGS_FRAGMENT));
            }

最佳答案

来自Objects.requireNonNull Javadoc

This method is designed primarily for doing parameter validation in methods and constructors

也就是说,使用它的好处是您的代码可以摆脱显式 if null 检查导致的一些噪音。

关于java - findFragmentByTag 中的 Null 检查与 Objects.requireNonNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57330806/

相关文章:

android - 如何在记录位置之前等待 GPS 修复

java - 我收到错误 "AWT-EventQueue-0"java.lang.NullPointerException 并且我不明白为什么在我的上下文中

java - 如何在 Spring mvc 中延迟方法的执行几毫秒?

java - error :undefined label, 如何在java中的这段代码中使用label语句?

android - 如何获取 4.4 kitkat 上的铃声 URI

android - 如何获取包括 subview 在内的布局中的 View 总数

java - 如果MutableLiveData正在更改,为什么我的ViewModel不调用.observe()并通知适配器?

java - Itext7 希伯来语反向问题

java - 无法解释 NullPointerException

android - 由于 'java.lang.NullPointerException',获取 Instrumentation 运行失败