我正在处理一个大型代码库,并且在很多地方看到这种类型的代码:
public static class RequestCustomData implements View.OnClickListener {
WeakReference<MainActivity> mainActivity;
public RequestCustomData(MainActivity activity) {
mainActivity = new WeakReference<>(activity);
}
@Override
public void onClick(View view) {
MainActivity activity = mainActivity.get();
activity.requestCustomData(true, null);
}
}
我有点疑惑为什么这么多地方用到这个?我查看了这份文档,但它并没有很好地阐明为什么这种类型的代码在我正在开发的应用程序中如此频繁地使用
https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references
如果这是一种常见模式,谁能给我解释一下?如果是,为什么?
最佳答案
A weak reference, simply put, is a reference that isn't strong enough to force an object to remain in memory.
如果 RequestCustomData
对象的生命周期可能超过 Activity 本身,则此代码的作者很可能希望避免泄漏 Activity 上下文。
我推荐Romain Guy's post on this topic以及要避免的几种特定情况:
关于android - 为什么在 Android Listeners 上使用 WeakReference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191755/