How to update annotation value in Kotlin
Answered
Hi
I wonder the properly way for update text value of annotation value argument?
At first I wrote this code:
fun updateAnnotationValueText(project: Project, annotation: KtAnnotationEntry, argumentName: String, newValueText: String) {
val valueArgExpression = annotation.valueArguments.find { it.getArgumentName()?.asName?.identifier == argumentName }?.getArgumentExpression()
WriteCommandAction.runWriteCommandAction(project) {
val newAttributeExpression = JavaPsiFacade.getElementFactory(project).createExpressionFromText(newValueText, valueArgExpression)
valueArgExpression?.replace(newAttributeExpression)
}
}
It works.
But if i try to change this value next time without editing/changing any in file, `.getArgumentExpression()` returns null
Because the argument expression type is PsiLiteralExpression, bun not KtStringTemplateExpression as at first time

Now i changed getting valueArgExpression to
val valueArgument = (annotation.valueArguments.find { it.getArgumentName()?.asName?.identifier == argumentName }as KtValueArgument).children.find { it is KtExpression || it is PsiExpression }
But it seams i miss something and there is more properly way.
Thanks in advance.
Please sign in to leave a comment.
Hi Alexander,
You operate on Kotlin code but use
JavaPsiFactory, which is dedicated for creating Java elements. Try to useorg.jetbrains.kotlin.psi.KtPsiFactory.That's what I need.
`KtPsiFactory(project).createExpression(newValueText)` works perfectly.
Thank you very much!