Using generic annotation classes from Java


#1

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?


#2

For any one looking into this the actual error is:

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

#3

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

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

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

#4

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?