既然ChatGPT能理解自然语言,为什么不让它来帮我写代码完成这个开发任务呢?
基于这个猜想,我尝试让它编写IDEA插件逻辑,以一个LOGGER插入为例。
我给的命令是
“
利用IntelliJ Platform Plugin SDK获取当前光标所在类的成员变量,检测是否存在LOGGER,如果不存在,在类声明的第一行插入LOGGER的声明,并import对应的slf4j依赖。用java实现
”
它给出的代码如下
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.Query; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Objects; public class AddLoggerToClassAction extends AnAction { private static final String LOGGER_DECLARATION = "private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(%s.class);"; private static final String SLF4J_IMPORT = "import org.slf4j.LoggerFactory;"; @Override public void actionPerformed(@NotNull AnActionEvent e) { // 获取当前项目和光标所在元素 PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE); Editor editor = e.getData(CommonDataKeys.EDITOR); Project project = e.getProject(); if (psiFile == null || editor == null || project == null) { return; } // 获取当前光标所在元素 PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset()); PsiClass psiClass = PsiUtil.getTopLevelClass(psiElement); if (psiClass == null) { return; } // 检查类中是否已经存在 LOGGER if (hasLogger(psiClass)) { return; } // 插入 LOGGER 声明并 import slf4j 依赖 PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project); PsiImportList importList = psiFile.getImportList(); if (importList != null && importList.findOnDemandImportStatement("org.slf4j") == null) { importList.add(elementFactory.createImportStatementOnDemand("org.slf4j")); } PsiField loggerField = elementFactory.createFieldFromText(String.format(LOGGER_DECLARATION, psiClass.getName()), psiClass); PsiElement firstElement = PsiUtilCore.findFirstNonWhitespaceElement(psiClass); psiClass.addBefore(loggerField, firstElement); } private static boolean hasLogger(PsiClass psiClass) { for (PsiField field : psiClass.getFields()) { if (Objects.equals(field.getType().getCanonicalText(), "org.slf4j.Logger") && Objects.equals(field.getName(), "LOGGER") && field.getModifierList().hasModifierProperty(PsiModifier.STATIC) && field.getModifierList().hasModifierProperty(PsiModifier.FINAL)) { return true; } } return false; } } |
对不起,是我高估了AI的实力,它部分代码在胡写。。。。得自己验证是否可行,它的代码看着没毛病,但实际很多地方都有问题= =
还是自己动手写吧,参考 https://www.bilibili.com/video/BV15D4y137Sp/
0 Comments