void (@NotNull final InsertionContext context) { final PsiFile file = context.getFile(); final PsiElement caretElement = Objects.requireNonNull(file.findElementAt(context.getEditor().getCaretModel().getOffset())); final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(context.getProject()); PsiElement newVariablePlacementAnchor; PsiElement newVarDeclarationTemplate; if (myField) { PsiField field = Objects.requireNonNull(PsiTreeUtil.getParentOfType(caretElement.getPrevSibling(), PsiField.class, false)); newVariablePlacementAnchor = field; PsiField newField = elementFactory.createField(myNewVarName, elementFactory.createType(myQualifierClass)); if (field.hasModifierProperty(PsiModifier.STATIC)) { PsiUtil.setModifierProperty(newField, PsiModifier.STATIC, true); } newVarDeclarationTemplate = newField; } else { newVariablePlacementAnchor = Objects.requireNonNull(PsiTreeUtil.getParentOfType(caretElement.getPrevSibling(), PsiStatement.class, false)); newVarDeclarationTemplate = elementFactory.createVariableDeclarationStatement(myNewVarName, elementFactory.createType(myQualifierClass), elementFactory.createExpressionFromText(PsiKeyword.NULL, null)); } PsiElement varDeclaration = newVariablePlacementAnchor.getParent().addBefore(newVarDeclarationTemplate, newVariablePlacementAnchor); JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(varDeclaration); }