How to read a Kotlin Annotation inside an intellij plugin?

Hi,

For Java, I can find annotation elements by checking if they are an instance of com.intellij.psi.PsiAnnotation. But I couldnt find anything similar to that in Kotlin. I have attached the debugger and checked element by element. But I couldn't find anything similar to PsiAnnotation which can provide all the details about the annoation in Kotlin. I get separate elements for the @ symbol and the annotation name.

@ -> PsiElement(AT)

MyAnnotation -> PsiElement(IDENTIFIER)

Any suggestions would be appreaciated. Thanks in advance. 

Thanks

0
Avatar
Permanently deleted user

After some investigation, I found an element called KtAnnotationEntry. But I still couldnt figure out on how to read the params of the annotation from KtAnnotationEntry. 

0

Hi! I usually do it somehow like this:

annotationEntry.valueArguments.firstOrNull { it.getArgumentName()?.asName?.asString() == name }?.getArgumentExpression() 

 

1
Avatar
Permanently deleted user

Thanks, @Nicolay for the suggestion. I am able to get the KtExpression object. But there is no way to read the value from it. I used the debugger and I can see the param value in this object. But it is not accessible. IntelliJ debugger comes up with this expression below to access this field,

(((myAnnotationId as KtConstantExpression).myNode as CompositeElement).firstChild as LeafPsiElement).myText

But myNode, firstChild, and myText are not accessible. 

I have an annotation like @MyAnnotation(123) and want to read the value 123 to use it. Is there any suggested way to read it? annotationEntry.text provides the whole annotation like in a string like "@MyAnnotation(123)". But reading from this string may break in future if the order changes with more than one param.

0
expression.getNode().getFirstChildNode()

should work.

Also, you could pass a visitor to the `accept` method to get inside the expression (probably you should use recursive visitor)

0
Avatar
Permanently deleted user

Thanks for the response @Nicolay. expression has no access to `getNode()`. I am not sure on how to use a visitor with an expression. I got the id value finally by

element.valueArguments[0].getArgumentExpression()?.getDebugText()

Not sure if it is an unofficial API! 

Thanks.

0

> expression has no access to `getNode()`

It is really strange, `KtExpression` inherits from `PsiElement` and `getNode` is a method of base `PsiElement` along with `accept` for visitors

0
Avatar
Permanently deleted user

Sorry, my bad. I didn't cast the ktExpression as PsiElement. I cast it to PsiElement and what you said worked perfectly.

(ktExpression as PsiElement).node.firstChildNode.text

Thank you so much :)

0

`KtExpression` type directly inherits `PsiElement` so it is very strange if you still need to cast if you have a variable of `KtExpression` type

Anyway, always glad to help)

 

1

请先登录再写评论。