How to enforce the method signature of a function at compile time

Viewed 25

I have a usecase where through reflection I invoke specific functions that are annotated uniquely. Here below MyClass and functionName have already been identified due to their annotation and are getting invoked.

MyClass.javaClass?.kotlin?.memberProperties?.find { function ->
        function == functionName
    }?.call(MyClass, params)

My concern is since these functions are written separately how do I ensure that these functions are always of the expected signature i.e. accepts a specific set of params that I define, because if not they would end up failing at runtime.

Is there a way to enforce a method signature contract through annotation?

The current approach I could come up with is to define a functional interface

fun interface MyHandler{ handle(params) }

and then create properties(rather than functions) that necessarily implement this functional interface (I'm hoping I will be able to filter properties that implement an interface)

var handler1 = MyHandler {params-> println("BL first $params")}
var handler2 = MyHandler {params-> println("BL second $params")}

But I do not know how to invoke such properties through reflection.

0 Answers
Related