ObjectReporter.kt
TLDR
The ObjectReporter.kt
file in the Demo Projects project defines a class called ObjectReporter
. This class enables implementations of ObjectInspector
to provide insights on a given object found in the heap.
Classes
ObjectReporter
The ObjectReporter
class represents a reporter for objects in the heap. It has the following properties:
-
heapObject
(HeapObject): The object in the heap that the reporter is associated with. -
labels
(LinkedHashSet<String>): Labels that will be visible on the correspondingheapObject
in the leak trace. -
leakingReasons
(MutableSet<String>): Reasons for which this object is expected to be unreachable (leaking). -
notLeakingReasons
(MutableSet<String>): Reasons for which this object is expected to be reachable (not leaking).
The class also has the following methods:
whenInstanceOf(expectedClass: KClass<out Any>, block: ObjectReporter.(HeapInstance) -> Unit)
Runs the specified block
if the ObjectReporter.heapObject
is an instance of the expectedClass
.
whenInstanceOf(expectedClassName: String, block: ObjectReporter.(HeapInstance) -> Unit)
Runs the specified block
if the ObjectReporter.heapObject
is an instance of the class with the expectedClassName
.
package shark
import shark.HeapObject.HeapInstance
import kotlin.reflect.KClass
/**
* Enables [ObjectInspector] implementations to provide insights on [heapObject], which is
* an object (class, instance or array) found in the heap.
*
* A given [ObjectReporter] only maps to one object in the heap, but is shared to many
* [ObjectInspector] implementations and accumulates insights.
*/
class ObjectReporter constructor(val heapObject: HeapObject) {
/**
* Labels that will be visible on the corresponding [heapObject] in the leak trace.
*/
val labels = linkedSetOf<String>()
/**
* Reasons for which this object is expected to be unreachable (ie it's leaking).
*/
val leakingReasons = mutableSetOf<String>()
/**
* Reasons for which this object is expected to be reachable (ie it's not leaking).
*/
val notLeakingReasons = mutableSetOf<String>()
/**
* Runs [block] if [ObjectReporter.heapObject] is an instance of [expectedClass].
*/
fun whenInstanceOf(
expectedClass: KClass<out Any>,
block: ObjectReporter.(HeapInstance) -> Unit
) {
whenInstanceOf(expectedClass.java.name, block)
}
/**
* Runs [block] if [ObjectReporter.heapObject] is an instance of [expectedClassName].
*/
fun whenInstanceOf(
expectedClassName: String,
block: ObjectReporter.(HeapInstance) -> Unit
) {
val heapObject = heapObject
if (heapObject is HeapInstance && heapObject instanceOf expectedClassName) {
block(heapObject)
}
}
}