PsiElement (@NotNull PsiType type, @NotNull String name, PsiExpression initializer) { PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); if (myAnchor instanceof PsiInstanceOfExpression && initializer instanceof PsiTypeCastExpression) { PsiTypeElement castType = Objects.requireNonNull(((PsiTypeCastExpression)initializer).getCastType()); return elementFactory.createExpressionFromText( ((PsiInstanceOfExpression)myAnchor).getOperand().getText() + " instanceof " + castType.getText() + " " + name, myContainer); } if (myContainer instanceof PsiClass) { PsiField declaration = elementFactory.createField(name, type); declaration.setInitializer(initializer); return declaration; } return elementFactory.createVariableDeclarationStatement(name, type, initializer, myContainer); }