Given an instance of a class, we can obviously return its name:
trait MixedInClassDiscovery {
val className = this.getClass.getName
}
class AClass extends MixedInClassDiscovery {
...
this.className // returns "AClass"
...
}
But this way uses reflection, once for every instance of AClass. Can the same be done once for every class, instead?
One solution which comes to mind is to mix it into companion objects instead of classes themselves.
I can’t think of any way to do it with no extra overhead. You could do it with companion objects, however, and a couple of extra pieces of work:
And here we see that this works:
but it comes at rather a price: you need to not only decorate the class with Discovery but also implement the companion method and write the companion object (which need not have the same name, incidentally) for every class.