PsiPatternVariable (@NotNull PsiPattern pattern, @NotNull PsiTypeElement typeElement, @NotNull PsiType type) { Project project = pattern.getProject(); PsiElementFactory factory = PsiElementFactory.getInstance(project); final JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project); String name = styleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type).names[0]; name = styleManager.suggestUniqueVariableName(name, pattern, true); /* If the pattern is not nested, we use the text of the operand matched against the pattern because the operand text of the created instanceof expression will be used in com.intellij.psi.util.JavaPsiPatternUtil.getEffectiveInitializerText. If the pattern is nested, we can use random text as operand text. */ PsiElement parent = pattern.getParent(); String operand = parent instanceof PsiInstanceOfExpression ? ((PsiInstanceOfExpression)parent).getOperand().getText() : "x"; String text = operand + " instanceof " + typeElement.getText() + " " + name; PsiInstanceOfExpression instanceOf = (PsiInstanceOfExpression)factory.createExpressionFromText(text, null); PsiPatternVariable variable = ((PsiTypeTestPattern)Objects.requireNonNull(instanceOf.getPattern())).getPatternVariable(); assert variable != null; return variable; }