xref: /aosp_15_r20/external/leakcanary2/shark/src/main/java/shark/ObjectReporter.kt (revision d9e8da70d8c9df9a41d7848ae506fb3115cae6e6)
1 package shark
2 
3 import shark.HeapObject.HeapInstance
4 import kotlin.reflect.KClass
5 
6 /**
7  * Enables [ObjectInspector] implementations to provide insights on [heapObject], which is
8  * an object (class, instance or array) found in the heap.
9  *
10  * A given [ObjectReporter] only maps to one object in the heap, but is shared to many
11  * [ObjectInspector] implementations and accumulates insights.
12  */
13 class ObjectReporter constructor(val heapObject: HeapObject) {
14 
15   /**
16    * Labels that will be visible on the corresponding [heapObject] in the leak trace.
17    */
18   val labels = linkedSetOf<String>()
19 
20   /**
21    * Reasons for which this object is expected to be unreachable (ie it's leaking).
22    */
23   val leakingReasons = mutableSetOf<String>()
24 
25   /**
26    * Deprecated, use leakingReasons instead.
27    */
28   @Deprecated(
29     "Replace likelyLeakingReasons with leakingReasons",
30     replaceWith = ReplaceWith(
31       "leakingReasons"
32     )
33   )
34   val likelyLeakingReasons
35     get() = leakingReasons
36 
37   /**
38    * Reasons for which this object is expected to be reachable (ie it's not leaking).
39    */
40   val notLeakingReasons = mutableSetOf<String>()
41 
42   /**
43    * Runs [block] if [ObjectReporter.heapObject] is an instance of [expectedClass].
44    */
whenInstanceOfnull45   fun whenInstanceOf(
46     expectedClass: KClass<out Any>,
47     block: ObjectReporter.(HeapInstance) -> Unit
48   ) {
49     whenInstanceOf(expectedClass.java.name, block)
50   }
51 
52   /**
53    * Runs [block] if [ObjectReporter.heapObject] is an instance of [expectedClassName].
54    */
whenInstanceOfnull55   fun whenInstanceOf(
56     expectedClassName: String,
57     block: ObjectReporter.(HeapInstance) -> Unit
58   ) {
59     val heapObject = heapObject
60     if (heapObject is HeapInstance && heapObject instanceOf expectedClassName) {
61       block(heapObject)
62     }
63   }
64 }