简体   繁体   中英

Intellij IDEA plugin development. Action “create kotlin class”

I want to create a plugin for Intellij IDEA . I need to add an action ( AnAction ) that will create a class in Kotlin (not Java) in a custom package . I have two questions:

  • How to create files with the desired extension?
  • Or how to create a file with Kotlin class (from some base class) in a custom package ?

实现此目的的一种可能方法是使用PsiFileFactory.createFileFromText()创建内存中的Kotlin文件,然后将该文件作为参数传递给PsiDirectory.add()以将其保存到文件系统。

Although yole's answer is correct, I would like to see more details about mistery PsiDirectory class.

//get directory by VirtualFile
PsiDirectory directory = PsiManager.getInstance(project).findDirectory((getKotlinSourceDir(project))

Get kotlin source dir:

private VirtualFile getKotlinSourceDir(Project project) {
    return project.getBaseDir().findChild("src").findChild("main").findChild("kotlin");
}

And than you can create subdirectories:

//someDirectoryName it is simple name 
//(i.e if you post "com.some.package" - it does not create com/some/package folder)
PsiDirectory newDirectory = psiDirectory.createSubdirectory(someDirectoryName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM