Is `javaClass` equal to `SomeClass::class.java`?
# announcements
z
Is
javaClass
equal to
SomeClass::class.java
?
a
javaClass refers to SomeClass.Companion and not to SomeClass
z
Mmm what is SomeClass.Companion?
If I don't have a companion object in SomeClass?
If you don't have a companion object in the class, then javaClass call won't compile
z
I have a springboot RestController, without companion object, and IntelliJ doesn't tell me anything if I try to use
javaClass
private val LOGGER = Logger.getLogger(javaClass)
a
This is interesting. If you want to access .javaClass like this:
SomeClass.javaClass
, then it won't compile without a companion object. But if you want to do it directly from the class, then it compiles and
javaClass == SomeClass::class.java
is true
let's wait for someone with more knowledge about it, I'm really curious now 🙂
h
javaClass
has nothing to do with companion objects. It just needs an instance, it's an equivalent to Java's
.getClass()
.
👍 1
Java's
String.class
is
String::class.java
Java's
"abc".getClass()
is
"abc".javaClass
(roughly)
k
But then
String.javaClass
would be the companion object's class if String had one.
👍 1
I think that's what he was saying.
h
ah, I didn't get that
z
That's a bit confusing honestly
What do you think would be the most elegant way to say
private val LOGGER = Logger.getLogger(javaClass)
, without having to worry if I have a companion object in the class or not?
k
If you're already in a class instance
javaclass
will always be the right one.
z
Perfect, thank you!
k
It's just that
MyClass.javaClass
can be the companion class, or it can be a compiler error.
👍 1