I'm trying to get the class that owns a companion object so I can create loggers with inline technique inside a companion object but referencing the main class that is being logged and not the companion object.
The problem is that I can't find a way to get the owner of the companion object, how can I do it?
fun Logger(c: Class<*>): Logger {
var c2 = c
val k = c.kotlin
if (k.isCompanion) {
c2 = k.<opposite of what companionObject does>.java
}
// Calls a factory, reuse the same instance if it already exists
return RootLogger.getChild(c2)
}
@Suppress("NOTHING_TO_INLINE")
inline fun Logger(): Logger {
return Logger(MethodHandles.lookup().lookupClass())
}
The intended use-cases:
A:
class SomeClass {
companion object {
// Logger is inside a companion object
// But it must be the same as if it were created directly inside `SomeClass`
private val log = Logger()
}
fun someFun() = log.info("Hello")
}
B:
// can be object or anything else
class SomeClass {
// The same object is returned to all instances and would be the same object
// as if it were inside a companion object
private val log = Logger()
fun someFun() = log.info("Hello")
}
Aucun commentaire:
Enregistrer un commentaire