Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify a Kotlin class

I'd like to write a plugin for Intellij IDEA that should modify a Java and Kotlin code.

I use the method

PsiClass.getMethods()

in order to get all methods of Java and Kotlin classes. So far so good, so then I use methods like

PsiClass.add(), PsiClass.addAfter(), PsiClass.addBefore()

that all work fine once they are called on Java files, but start to throw an exception

IncorrectOperationException

once I called them on a Kotlin class.

I'd appreciate any hint on how I can modify Kotlin and Java classes (preferably using the same approach).

like image 330
Andrew Avatar asked Jul 26 '26 17:07

Andrew


1 Answers

When you search for a Kotlin class via the JavaPsiFacade, it returns the light class which is a shallow representation that is just based on the information in the class file. In order to add PSI elements, you have to call navigationElement on it. Then, IJ will parse the source and build a full PSI tree that can be modified.

However, if the class is a Kotlin class, navigationElement will return a KtClass which is not derived from PsiClass. You will have to use the facilities in the Kotlin hierarchy to modify it. Method instances in Kotlin are also not instances of PsiMethod, but instances of KtMethod.

For analyzing Java and Kotlin sources in a common fashion there is a different syntax tree called "UAST", but for modifications you need a language-specific approach.

like image 162
Ingo Kegel Avatar answered Jul 28 '26 13:07

Ingo Kegel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!