3
votes

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).

1

1 Answers

6
votes

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.