Creating a new class

At some point in my plugin i want to create a new class in a given package in the current module from a class template.

Although this sounds simple is has lots of things that have to be taken care of before you actually create the class. Some of these are:

- What if the package doesn't exist ? I have to check if the package is created and if not create it myself.
- In which source root should the class/package be created ? I have to implement a source root selector dialog for this.

There may be more but these are the ones i thought of instantly.

Anyway, the question is:

Is there anything in the open api that already takes care of all this for me ?

Thanks....

0
5 comments
Avatar
Permanently deleted user

At least if i can use the source root selector dialog that IDEA has ?

0
Avatar
Permanently deleted user

You might find some useful stuff for that in com.intellij.ide.util.PackageUtil

HTH,
Sascha

0
Avatar
Permanently deleted user

Once you locate the source root directory (there are several ways of doing so) you can use the following methods to create the directory structure for a package. Note that they will only create a new directory if it does not already exist. Also, be sure to use these inside a WriteCommandAction.

public static PsiDirectory createDirectory(PsiDirectory parent, String name)
throws IncorrectOperationException {
PsiDirectory result = null;

for (PsiDirectory dir : parent.getSubdirectories()) {
if (dir.getName().equalsIgnoreCase(name)) {
result = dir;
break;
}
}

if (null == result) {
result = parent.createSubdirectory(name);
}

return result;
} // createDirectory()

public static PsiDirectory createPackage(PsiDirectory sourceDir, String qualifiedPackage)
throws IncorrectOperationException {
PsiDirectory parent = sourceDir;
StringTokenizer token = new StringTokenizer(qualifiedPackage, ".");
while (token.hasMoreTokens()) {
String dirName = token.nextToken();
parent = createDirectory(parent, dirName);
}
return parent;
} // createPackage()

0
Avatar
Permanently deleted user

Hello,

I am asking how to add or create a new java class in a PsiDirectory ?

0
Avatar
Permanently deleted user

Hello,
You can use JavaDirectoryService class. The class has several methods that allows you to create a java class in a given directory

JavaDirectoryService.createClass(PsiDirectory dir, String name) -- allows you to create a java class in a a given directory.


Or you can use

JavaDirectoryService.createClass(PsiDirectory dir, String name, String templateName)  -- allows to create a java class using file template



and specify a file template for this. If you going to use templates you should create freemarketer template and register it in plugin.xml via <internalFileTemplate> extention point.
0

Please sign in to leave a comment.