有没有办法强制仅在 var 属性 上使用注释

Is there a way to force using annotation only on a var property

根据法律,我正在制作一个用于加密个人数据的注释处理器。因此,为了加密这些字段,它应该能够设置新值,所以我希望我的注释仅在 var 属性.

上强制使用
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.FIELD, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
annotation class PersonalData {
}

data class CreateAccountCommand(
  @PersonalData
  var fullname: String // it would throw an error if using val since it's not mutable
)

class TestAnnotation {
  @Test
  fun testFindAnnotation() {
    val message = EasyRandom().nextObject(CreateAccountCommand::class.java)
    val wrappedCommand = GenericCommandMessage.asCommandMessage<CreateAccountCommand>(message)
    if (isPersonalDataPresent(wrappedCommand.payload)) {
      encryptData(wrappedCommand.payload)
      wrappedCommand.payload.fullname shouldContain "-encrypted"
    }
  }

  private fun isPersonalDataPresent(payload: Any): Boolean {
    return payload::class.memberProperties.any {
      it.annotations.any { ann -> ann.annotationClass == PersonalData::class }
    }
  }

  private fun encryptData(payload: Any) {
    payload::class.memberProperties.map {
      if (it is KMutableProperty<*>) {
        it.setter.call(payload, "${it.getter.call(payload)}-encrypted")
      }
    }
  }
}

或者有更好的方法吗?

如果您只在注释目标中包含 PROPERTY_SETTER,则注释只能应用于 属性 setters,这实际上是您想要的 - 因为 属性 setter 隐含一个可变的属性.

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY_SETTER)
annotation class PersonalData

使用此注释时,通常必须指定使用站点目标:

data class CreateAccountCommand(
    @set:PersonalData
    var fullname: String
)

将其更改为 val 会给您一个错误,正如您预期的那样,因为 val 没有 setter。

isPersonalDataPresent也需要稍微修改一下,查看setter是否有注解:

return payload::class.memberProperties
    .filterIsInstance<KMutableProperty<*>>()
    .any {
        it.setter.annotations.any { ann ->
            ann.annotationClass == PersonalData::class
        }
    }