private static PsiField createField( PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) { @NonNls StringBuilder pattern = new StringBuilder(); pattern.append("private int "); pattern.append(fieldName); if (local.getInitializer() == null) { includeInitializer = false; } if (includeInitializer) { pattern.append("=0"); } pattern.append(";"); final Project project = local.getProject(); PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); try { PsiField field = factory.createFieldFromText(pattern.toString(), null); field.getTypeElement().replace(factory.createTypeElement(forcedType)); if (includeInitializer) { PsiExpression initializer = RefactoringUtil.convertInitializerToNormalExpression( local.getInitializer(), forcedType); field.getInitializer().replace(initializer); } for (PsiAnnotation annotation : local.getModifierList().getAnnotations()) { field.getModifierList().add(annotation.copy()); } return field; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
private static void initialize(final PsiLocalVariable variable) throws IncorrectOperationException { PsiType type = variable.getType(); String init = PsiTypesUtil.getDefaultValueOfType(type); PsiElementFactory factory = JavaPsiFacade.getInstance(variable.getProject()).getElementFactory(); PsiExpression initializer = factory.createExpressionFromText(init, variable); variable.setInitializer(initializer); }
public IntroduceFieldRunnable( boolean rebindNeeded, PsiLocalVariable local, PsiClass aClass, BaseExpressionToFieldHandler.Settings settings, boolean isStatic, PsiExpression[] occurrences) { myVariableName = local.getName(); myFieldName = settings.getFieldName(); myRebindNeeded = rebindNeeded; myLocal = local; myProject = local.getProject(); myDestinationClass = aClass; mySettings = settings; myInitializerPlace = settings.getInitializerPlace(); myOccurences = occurrences; }
private static PsiStatement createAssignment( PsiLocalVariable local, String fieldname, PsiElementFactory factory) { try { String pattern = fieldname + "=0;"; PsiExpressionStatement statement = (PsiExpressionStatement) factory.createStatementFromText(pattern, null); statement = (PsiExpressionStatement) CodeStyleManager.getInstance(local.getProject()).reformat(statement); PsiAssignmentExpression expr = (PsiAssignmentExpression) statement.getExpression(); final PsiExpression initializer = RefactoringUtil.convertInitializerToNormalExpression( local.getInitializer(), local.getType()); expr.getRExpression().replace(initializer); return statement; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }