Idea插件添加EditorPopupMenu显示JAVA对象的
2019-08-20 本文已影响42人
艺术类架构师
第一步:创建IntelliJ Platform Plugin工程 new->->IntelliJ Platform Plugin
第二步:右击Project new Action
图片.png
第三步:编辑JAVABeanToJSONAction类写代码
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.psi.*;
import com.intellij.ui.JBColor;
import java.awt.*;
/**
* Created by Administrator on 2019/8/20.
*/
public class JAVABeanToJSONAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent event) {
Editor editor = event.getData(PlatformDataKeys.EDITOR);
PsiFile psiFile = event.getData(LangDataKeys.PSI_FILE);
//只读文件直接返回
if( psiFile.getFileType().isReadOnly()){
return;
}
//不是JAVA类直接返回
if(!psiFile.getVirtualFile().getName().contains(".java")){
return;
}
Messages.showInfoMessage(editor.getProject(),psiFile.getVirtualFile().getName(),"");
// 遍历当前对象的所有属性
for (PsiElement psiElement : psiFile.getChildren()) {
System.out.println(psiElement);
if (psiElement instanceof PsiClass) {
PsiClass psiClass = (PsiClass) psiElement;
String json = genJsonStringForPsiClass(psiClass);
showPopupBalloon(editor, json);
}
}
}
private String genJsonStringForPsiClass(PsiClass psiClass){
StringBuilder sbd=new StringBuilder("{");
PsiField[] psiFields= psiClass.getAllFields();
if(null!=psiFields&&psiFields.length>0){
for(int i=0,size=psiFields.length;i<size;i++){
String name= psiFields[i].getName();
sbd.append('"').append(name).append('"');
sbd.append(":").append('"').append('"');
if(i!=size-1){
sbd.append(",");
}
}
}
return sbd.append("}").toString();
}
private void showPopupBalloon(final Editor editor, final String result) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
JBPopupFactory factory = JBPopupFactory.getInstance();
factory.createHtmlTextBalloonBuilder(result, null, new JBColor(new Color(186, 238, 186), new Color(73, 117, 73)), null)
.setFadeoutTime(5000)
.createBalloon()
.show(factory.guessBestPopupLocation(editor), Balloon.Position.below);
}
});
}
}
第四步:build插件工程
图片.png
第五步:install plugin from Desk,完成之后重启IDEA
图片.png
重启之后点击任何JAVA类右击之后会出现一个子菜单
图片.png
效果图如下:
图片.png