0

Let's suppose that I have a one interface. interface example And I have class A, B, C that inherits example.(And I will make more) I need to get a class that inherits example randomly. So I want to save the information of A, B, C as a list. But they have constructor that need user's input. So I need to save classes but instance. How can I do this? If there's a better way to solve this (not saving classes as a list), please give me an advice.

kdm1jkm
  • 5
  • 1
  • All classes use the same type and number of parameters in the constructors? – Diego Marin Santos Apr 11 '20 at 22:49
  • @DiegoMarin Yes their constructors are (and will be) all the same. – kdm1jkm Apr 12 '20 at 08:38
  • Can't you store instances and access the type information with `.javaClass`? – Commander Tvis Apr 12 '20 at 13:58
  • @CommanderTvis There is primary constructor that has parameter that need user's input so I can't make and store instance. But I finally found a way to solve. I decided to user ```kclass<>``` to store ```A```, ```B```, ```C``` but I can't make instance from ```kclass<>```(with parameters.) It keep making errors. Do you know how to make instance from ```kclass<>``` with parameters? If you know, please give me an advice. – kdm1jkm Apr 13 '20 at 01:39
  • @kdm1jkm `val klass = something::class; klass.primaryConstructor!!.call(args)` – Commander Tvis Apr 13 '20 at 09:52

1 Answers1

0

That's an example of how you can do it:

import kotlin.reflect.full.primaryConstructor

interface MyInterface {
    fun doSomething()
}

class A(param1: Int, param2: Int) : MyInterface {
    override fun doSomething() {
        TODO("Not yet implemented")
    }
}

class B(param1: Int, param2: Int) : MyInterface {
    override fun doSomething() {
        TODO("Not yet implemented")
    }
}

fun main() {
    val list = listOf(A::class.primaryConstructor, B::class.primaryConstructor)
    val instance = list.random()?.call(1, 2)
    instance?.doSomething()
}

But I'm considering you will hardcode the classes in the list. If you want to make it dynamically, take a look at this Find Java classes implementing an interface

Diego Marin Santos
  • 1,923
  • 2
  • 15
  • 29