public static PsiMethod generateSetterPrototype( PsiField field, final PsiClass containingClass, boolean returnSelf) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); String name = field.getName(); boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); VariableKind kind = codeStyleManager.getVariableKind(field); String propertyName = codeStyleManager.variableNameToPropertyName(name, kind); String setName = suggestSetterName(project, field); try { PsiMethod setMethod = factory.createMethod( setName, returnSelf ? factory.createType(containingClass) : PsiType.VOID); String parameterName = codeStyleManager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER); PsiParameter param = factory.createParameter(parameterName, field.getType()); annotateWithNullableStuff(field, factory, param); setMethod.getParameterList().add(param); PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); @NonNls StringBuffer buffer = new StringBuffer(); buffer.append("{\n"); if (name.equals(parameterName)) { if (!isStatic) { buffer.append("this."); } else { String className = containingClass.getName(); if (className != null) { buffer.append(className); buffer.append("."); } } } buffer.append(name); buffer.append("="); buffer.append(parameterName); buffer.append(";\n"); if (returnSelf) { buffer.append("return this;\n"); } buffer.append("}"); PsiCodeBlock body = factory.createCodeBlockFromText(buffer.toString(), null); setMethod.getBody().replace(body); setMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(setMethod); return setMethod; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }
public static PsiMethod generateGetterPrototype(PsiField field) { PsiElementFactory factory = JavaPsiFacade.getInstance(field.getProject()).getElementFactory(); Project project = field.getProject(); String name = field.getName(); String getName = suggestGetterName(project, field); try { PsiMethod getMethod = factory.createMethod(getName, field.getType()); PsiUtil.setModifierProperty(getMethod, PsiModifier.PUBLIC, true); if (field.hasModifierProperty(PsiModifier.STATIC)) { PsiUtil.setModifierProperty(getMethod, PsiModifier.STATIC, true); } annotateWithNullableStuff(field, factory, getMethod); PsiCodeBlock body = factory.createCodeBlockFromText("{\nreturn " + name + ";\n}", null); getMethod.getBody().replace(body); getMethod = (PsiMethod) CodeStyleManager.getInstance(project).reformat(getMethod); return getMethod; } catch (IncorrectOperationException e) { LOG.error(e); return null; } }