Using generic annotation classes from Java

Is it possible to use annotation classes from Java if they have generics?

Kotlin (as opposed to Java) supports generics for annotation classes (Java’s @interface).

interface Contract
class ContractImpl: Contract

annotation class Annotated<C: Contract>(val contract: KClass<C>)

@Annotated<ContractImpl>(ContractImpl::class)
fun function() {}

However, when I try to use this annotation from Java, I get an error “Incompatible types. Found: 'java.lang.Class, required: ‘java.lang.Class’”

@Annotated(contract = ContractImpl.class)
void function() {}

Since I cannot do @Annotated<ContractImpl> in Java, is there any way to use this annotation?

1 Like

For any one looking into this the actual error is:

Incompatible types. Found: 'java.lang.Class<ContractImpl>, required: ‘java.lang.Class<C>'

Wouldn’t it be easier to just declare annotation like this?

annotation class Annotated(val contract: KClass<out Contract>)

@Annotated(ContractImpl::class)
fun function() {}

Well that works aroudn the problem at best but my real world case is closer to

annotation class Annotated<C: Contract>(val contract1: KClass<C>, val contract2: KClass<C>)

which gives extra restrictions on the type of contract1 and contract2, but I do not see how to use it from Java?

2 Likes