What is the difference between Foo :: class.java and Foo :: javaClass?

To initialize my registrar, apparently I need:

val LOGGER : Logger = LoggerFactory.getLogger(Foo::class.java);

If I do this:

val LOGGER : Logger = LoggerFactory.getLogger(Foo::javaClass);

He complains that the parameter type is not compatible with getLogger. However, according to the API, both values Class<Foo>. How do they differ?

+4
source share
3 answers

javaClassis an extension property that returns the Java class of the runtime of an instance of an object . In your case, it is used as a reference to a property that will give you KProperty1<Foo, Class<Foo>>an extension function:

val T.javaClass: java.lang.Class<T>

You can use this in combination with a receiver, for example. if Fooprovided a default constructor, you could say:

Foo::javaClass.get(Foo())

which can be simplified to:

Foo().javaClass

::class.java, Java Class<?>, " " . :

val kProperty1: KProperty1<Foo, Class<Foo>> = Foo::javaClass
kProperty1.get(Foo()) //class de.swirtz.kotlin.misc.Foo
Foo::class.java //class de.swirtz.kotlin.misc.Foo
Foo().javaClass //class de.swirtz.kotlin.misc.Foo
+5

javaClass - , Java .

/**
 * Returns the runtime Java class of this object.
 */
public inline val <T: Any> T.javaClass : Class<T>
    @Suppress("UsePropertyAccessSyntax")
    get() = (this as java.lang.Object).getClass() as Class<T>

, :

println(Foo().javaClass)    //class Foo

Foo::javaClass KProperty1<Foo, Class<Foo>> Java, Foo :

val p: KProperty1<Foo, Class<Foo>> = Foo::javaClass
println(p.get(Foo()))    //p.get(Foo()) returns a Java class Foo

KProperty LoggerFactory.getLogger(), Java.

+4

Foo::javaClass val,

inline val <T : Any> T.javaClass: Class<T>

, Foo, foo.javaClass.

Foo::class KClass of Foo java KClass,

val <T> KClass<T>.java: Class<T>
+2

Source: https://habr.com/ru/post/1687099/


All Articles