MainActivity.kt:
class MainActivity : AppCompatActivity() {
private val printers = Printers()
private val strongObject = object: Item {
override fun print(): Int {
return Log.e("MainActivity", "strongObject")
}
}
private val strongSAM = {
Log.e("MainActivity", "strongSAM")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val localObject = object: Item {
override fun print(): Int {
return Log.e("MainActivity", "localObject")
}
}
val localSAM = {
Log.e("MainActivity", "localSAM")
}
printers.add(strongObject)
printers.add(strongSAM)
printers.add(localObject)
printers.add(localSAM)
findViewById<TextView>(R.id.content).setOnClickListener {
printers.dump()
}
}
}
Item.java:
public interface Item {
int print();
}
Printers.java:
public class Printers {
List<WeakReference<Item>> list = new ArrayList<>();
public void add(final Item item) {
list.add(new WeakReference<>(item));
}
public void dump() {
Log.e("Printers", "Size: " + list.size());
for (final WeakReference<Item> item: list) {
if (item.get() != null) {
item.get().print();
}
}
}
}
输出:
Size: 4
strongObject
如果运行此程序,您会注意到垃圾收集器将垃圾收集StrongSAM,localSAM和localObject。但是strongSAM有很强的参考意义,如何收集垃圾?
从生成的类的类查看器中,strongSAM确实是一个字段,并且具有很强的引用。