开发中 我们经常需要再dao.java 和mapper.xml 中来回切换。每次找mapper的时候有点麻烦。就想找一个能直接冲dao方法中跳到mapper文件中的插件。找到后是收费的,就想自己搞个插件。
创建插件项目 new-project
image选择 IntelliJ Platform Plugin
imagenext
image填写项目名称和路径 finish
src 文件夹 右键
image选择action 出现如下窗口
填写信息
选择JavaGenerateGroup1
first 设置快捷键
ok
imagectrl+shift+alt+x 快捷键有可能会被占用 建议先查询下快捷键是否被占用,在使用
确定后 plugin 文件 actions 会增加一个action
imagesrc 中增加 文件
imageaction文件 代码
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.PsiShortNamesCache;
import com.intellij.psi.xml.XmlFile;
public class GoToMapperAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
//获取鼠标所在元素
PsiElement psiElement = e.getData(PlatformDataKeys.PSI_ELEMENT);
if (psiElement == null){
return;
}
//获取到方法名
String methodName = psiElement.toString().replace("PsiMethod:","");
//获取方法的父元素
PsiElement psiElementParent = psiElement.getParent();
if (psiElementParent == null){
return;
}
//获取到文件,这里是java类
PsiFile containingFile = psiElementParent.getContainingFile();
//获取到类名
String className = containingFile.getName();
String mapperName ;
if (className.endsWith("Service.java")) {
mapperName = className.replace("Service.java", "Mapper.xml");
}
else if (className.endsWith("Dao.java")) {
mapperName = className.replace("Dao.java", "Mapper.xml");
}
else {
return;
}
Project project = e.getProject();
//查找名称为mapperName的文件
PsiFile[] files = PsiShortNamesCache.getInstance(project).getFilesByName(mapperName);
if (files.length == 1) {
XmlFile xmlFile = (XmlFile) files[0];
XmlTag[] subTags = xmlFile.getDocument().getRootTag().getSubTags();
for (XmlTag subTag : subTags) {
XmlAttribute[] attributes = subTag.getAttributes();
for (XmlAttribute attribute : attributes) {
if (attribute.getName().equals("id")){
if (attribute.getValue().equals(methodName)){
offset = attribute.getTextOffset();
OpenFileDescriptor openFileDescriptor = new OpenFileDescriptor(project, files[0].getVirtualFile(),offset);
FileEditorManager.getInstance(project).openTextEditor(openFileDescriptor, true);
}
}
}
}
}
}
}
网友评论