##一、描述
此文章介绍Studio插件开发所使用的API介绍
##二、方法
Project
//获取此项目的Project对象
Project project = e.getData(PlatformDataKeys.PROJECT)
project.getName(); //返回此项目名称
project.getBasePath(); //此方法是返回这个项目的完整路径,比如:C:/Users/junwen/IdeaProjects/Test
VirtualFile[] children = project.getBaseDir().getChildren(); //返回此项目下的所有子文件夹
for (VirtualFile child : children) {
System.out.println(child.getName()); //遍历打印文件夹名字 : out,src,.idea,Test.iml,resources
}
复制代码
Editor
Editor editor = e.getData(PlatformDataKeys.EDITOR); //获取编辑器对象
editor.getCaretModel().getCurrentCaret().getSelectedText(); //获取当前选中的文本信息
editor.getSelectionModel().getSelectedText(); //这样也能获取当前选中的文本
复制代码
PsiFIle PsiClass PsiElementFactory
PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);//获取这两个对象的一个总类
PsiClass targetClass = getTargetClass(editor, psiFile) //返回这个类的对象
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); // 获取元素操作的工厂类
复制代码
##三、示例
###(一)生成代码
Action动作操作类
public class CreateMethod extends BaseGenerateAction {
public CreateMethod() {
super(null);
}
public CreateMethod(CodeInsightActionHandler handler) {
super(handler);
}
@Override
public void actionPerformed(AnActionEvent e) {
// TODO: insert action logic here
//获取项目对象
Project project = e.getData(PlatformDataKeys.PROJECT);
//获取编辑对象
Editor editor = e.getData(PlatformDataKeys.EDITOR);
//根据2个对象组成这个文件
PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
//返回当前类的对象
PsiClass targetClass = getTargetClass(editor, psiFile);
//返回一个元素操作的工厂类
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
//最后执行代码生成类
new CodeGenerate(project,factory,targetClass,psiFile).execute();
}
}
复制代码
代码生成类
/**
* 代码生成类,继承WriteCommandAction.Simple
*/
public class CodeGenerate extends WriteCommandAction.Simple {
private Project project;
private PsiFile psiFile;
private PsiElementFactory factory;
private PsiClass targetClass;
protected CodeGenerate(Project project, PsiElementFactory factory, PsiClass targetClass, PsiFile... files) {
super(project, files);
this.project = project;
this.psiFile = files[0];
this.factory = factory;
this.targetClass = targetClass;
}
protected void run() throws Throwable {
//组装需要生成的代码
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("public void view(JTextField jTextField){\n" +
" \n" +
" }");
//把需要生成的代码通过工厂类生成成为方法,并且加入到此类当中
targetClass.add(factory.createMethodFromText(stringBuffer.toString(), targetClass));
//下面的不知道有什么特别的用处,随意加不加
JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
styleManager.optimizeImports(psiFile);
styleManager.shortenClassReferences(targetClass);
}
}
复制代码
##五、注意事项
####在运用IDE开发插件的时候,有的时候会发现运行后,看不到你设置的按钮在那个选项卡下面,这个原因有很多种,可以按以下方法设置:
1 删除所有安装过的插件,清理干净
2 类名和Action按钮的名字相同