Kotlin集成与测试:提升Java与Kotlin互操作性
1. 默认目标与注解使用
如果添加的注解未指定使用位置,目标将根据注解上指定的目标来选择。例如自定义注解:
@Target(AnnotationTarget.PROPERTY_GETTER)
annotation class ColorRes
这个注解只能应用于属性的getter方法,以下代码无法编译:
class ViewModel( @ColorRes val resId:Int )
但如果指定get使用位置,代码就能正常编译:
class ViewModel( @get:ColorRes val resId:Int )
如果注解声明中不包含 @Target
注解,以下目标是适用的:
- class
- property
- field
- local_variable
- value_parameter
- constructor
- function
- property_getter
- property_setter
利用这些目标可以改善注解在Kotlin和Java中的识别和使用。
为了更好地理解Kotlin与Java的互操作性,我们还