Set<PsiVariable> (PsiCodeBlock block) { final HashSet<PsiVariable> result = new HashSet<>(); PsiElement[] children = block.getChildren(); for (PsiElement child : children) { child.accept(new JavaElementVisitor() { @Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) { visitReferenceElement(expression); } @Override public void visitDeclarationStatement(@NotNull PsiDeclarationStatement statement) { PsiElement[] declaredElements = statement.getDeclaredElements(); for (PsiElement declaredElement : declaredElements) { if (declaredElement instanceof PsiVariable) result.add((PsiVariable)declaredElement); } } @Override public void visitForStatement(@NotNull PsiForStatement statement) { super.visitForStatement(statement); final PsiStatement initialization = statement.getInitialization(); if (!(initialization instanceof PsiDeclarationStatement declarationStatement)) { return; } final PsiElement[] declaredElements = declarationStatement.getDeclaredElements(); for (final PsiElement declaredElement : declaredElements) { if (declaredElement instanceof PsiVariable) { result.add((PsiVariable)declaredElement); } } } }); } return result; }