【发布时间】:2018-10-18 07:50:35
【问题描述】:
这种方法看起来非常棒,但是,当将它与生产代码一起使用并将它用于可能为空的对象时,它看起来很笨拙。考虑我的例子:
public class ShowDialogTask extends AsyncTask<Void, Void, Void> {
private WeakReference<Context> contextReference;
public ShowDialogTask(Context context) {
contextReference = new WeakReference<>(context);
}
@Override
protected Void doInBackground(Void... voids) {
...do a long running task...
return null;
}
@Override
protected void onPostExecute(Void void) {
super.onPostExecute(void);
Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Dialog title");
builder.setCancelable(true);
builder.create().show();
}
在 onPostExecute() 函数中,我使用 Objects.requireNonNull 方法设置了一个局部变量对象 ctx。我的问题是,让 contextReference.get() 等于 null 对我来说有点难以重现,而且它绝对有可能在生产中发生。
我想知道将此功能用于生产目的的最佳方式。
我的第一个想法是将代码包装在 try-catch 中,但在任何地方都这样做似乎是糟糕的编程:
try {
Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Dialog title");
builder.setCancelable(true);
builder.create().show();
} catch (Throwable t) {
Log.d(TAG, t.getMessage());
}
【问题讨论】:
-
requireNonNull通常用于应该从不为空的东西。不是您期望有时为空的东西。 -
如果您不知道如何处理它们,则永远不要捕获运行时异常,只有在您可以采取措施时才捕获它们。否则,您将隐藏随着时间的推移而积累的潜在问题,并且当一切停止工作时您将很难解决。
-
@khelwood 谢谢,我相信这就是我想要的澄清。
标签: java android nullpointerexception null