kotlin反射class.java和javaClass区别

kotlin反射class.java和javaClass区别

kotlin文件的类

class Person {
    var name: String = ""
    var age: Int = 0
}

java文件的类

public class Cat {

}

测试代码:

fun main(args: Array) {
    val person = Person()
    val cat = Cat()
    println("person::class=${person::class}")//得到的是KClass和Person::class一样
    println("person::class.java=${person::class.java}")//得到的是Class对象
    println("person::javaClass=${person::javaClass}")//未知?
    println("person.javaClass.kotlin=${person.javaClass.kotlin}")//得到的是Class对象
    println("cat.javaClass.kotlin=${cat.javaClass.kotlin}")//拿到的是KClass
    println("Cat::class.java=${Cat::class.java}")//得到的Class
    println("cat.javaClass == Cat::class.java=${cat.javaClass == Cat::class.java}")//Class==Class
    println("person.javaClass == Person::class.java=${person.javaClass == Person::class.java}")//Class==Class
    println("person.javaClass.kotlin == Person::class=${person.javaClass.kotlin == Person::class}")//KClass==KClass
    println("cat.javaClass.kotlin == Cat::class=${cat.javaClass.kotlin == Cat::class}")//KClass==KClass
}

输出结果:

person::class=class Person (Kotlin reflection is not available)
person::class.java=class Person
person::javaClass=property javaClass (Kotlin reflection is not available)
person.javaClass.kotlin=class Person (Kotlin reflection is not available)
cat.javaClass.kotlin=class Cat (Kotlin reflection is not available)
Cat::class.java=class Cat
cat.javaClass == Cat::class.java=true
person.javaClass == Person::class.java=true
person.javaClass.kotlin == Person::class=true
cat.javaClass.kotlin == Cat::class=true

Process finished with exit code 0

总结:
Cat::class.java和cat.javaClass都表示Class
person.javaClass.kotlin == Person::class都表示KClass

你可能感兴趣的:(kotlin)