I have two classes which might look like this
class MyClass {
var myProperty: AnotherClass?
}
class AnotherClass {
}
Through reflection I iterate the properties of MyClass and when I find a KMutableProperty<*>
which is null I want to create an instance of that class. Right now I'm doing something like this
val instance = MyClass()
val property = MyClass::myProperty
var subInstance = it.getter.call(instance)
if (subInstance == null) {
it.setter.call(instance, property.returnType.jvmErasure.createInstance())
}
but this seems like a terrible hack that needs to know internals and use Java magic instead of being pure Kotlin, is there a proper way to do what I want? Or is this the proper way?
1.0. interface KType : KAnnotatedElement. Represents a type. Type is usually either a class with optional type arguments, or a type parameter of some declaration, plus nullability.
Represents a class and provides introspection capabilities. Instances of this class are obtainable by the ::class syntax.
The KClass type is Kotlin's counterpart to Java's java. lang. Class type. It's used to hold references to Kotlin classes; you'll see what it lets you do with those classes in the “Reflection” section later in this chapter. The type parameter of KClass specifies which Kotlin classes can be referred to by this reference.
Instance method in Python. Last Updated : 02 Jul, 2020. A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes ...
Instances in Java are known as Objects. An object is a real-life entity, whereas a Class is a group of similar objects. An object is created from the class. Dog is a class that is a real-life entity.
Class instances can also have methods (defined by its class) for modifying its state. Note: For more information, refer to Python Classes and Objects Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute.
As a reminder, an instance is a concrete occurrence of a class object. For our instance, let’s set attributes corresponding to one of my favorite YouTube channels, sentdex: Now that we’ve created our instance, let’s print out the instance: We see that we have an object of type ‘YouTube’ at the specified memory address.
You can use (property.returnType.classifier as KClass).createInstance()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With