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 PsiField createField( PsiLocalVariable local, PsiType forcedType, String fieldName, boolean includeInitializer) { @NonNls StringBuilder pattern = new StringBuilder(); pattern.append("var "); pattern.append(fieldName); PsiType type = local.getType(); if (local.getInitializer() == null) { includeInitializer = false; } else { type = local.getInitializer().getType(); } pattern.append(": ").append(type.getPresentableText()); if (includeInitializer) { pattern.append(" = ").append(local.getInitializer().getText()); } final PsiElement psiElement = GosuPsiParseUtil.parseProgramm( pattern.toString(), PsiManager.getInstance(local.getProject()), null); final GosuFieldImpl field = PsiTreeUtil.findChildOfType(psiElement, GosuFieldImpl.class); GeneratedMarkerVisitor.markGenerated(field); try { final PsiModifierList modifierList = local.getModifierList(); if (modifierList != null) { for (PsiAnnotation annotation : modifierList.getAnnotations()) { field.getModifierList().add(annotation.copy()); } } return field; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }