How to add data members and its setter getters while creating a new class file

I am developing a plugin which has to create class with data members(taken from users) and its setter getters. 

As of now i am able to create class files with below method.

JavaDirectoryService.getInstance().createClass(dir, className, templateName, true);

If i pass all my parameters in a map to the below function, i cant see those members in the created class file! 

HashMap<String, String> parameters = new HashMap<>();
parameters.put("data","String");
JavaDirectoryService.getInstance().createClass(dir, className, templateName, true, parameters);

Am i missing something here? 

0
5 comments

The parameters are passed to the template and could be used there. Please share the template text you have and what parameters you pass. 

Thanks,

Anna

0
Avatar
Permanently deleted user

HI Anna,

I figured out that i need to create a template in order to pass the parameters. I dont have a template, i am using default class template.

 

My requirement is to create classes, add data members to them and the corresponding setter getters. 

Is there any way to achieve the same without creating a template class.

 

Thanks,

Guru

 

0
Avatar
Permanently deleted user

I created a class like this.

 

PsiClass newClass = checkOrCreate(fname,dir, "Class", parameters);

Then using the PsiClass object if i try to add new fields, 

 

PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());

PsiField field = elementFactory.createField("sampleVar", PsiType.INT);
PsiElement el = psiClass.add(field);
JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(el);

Its throwing an exception. 

Must not change PSI outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor com.intellij.util.IncorrectOperationException: Must not change PSI outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor

 

 

 

0

As the message advice: you need to wrap write operations (add field to a class) with a command, so undo would be possible. Please note that write PSI is possible in EDT thread only.

0
Avatar
Permanently deleted user

yes, that resolved the issue. thank you.

0

Please sign in to leave a comment.