generate toString to ensure valid method name/signature (IDEA-183995)

This commit is contained in:
Anna.Kozlova
2017-12-20 16:11:31 +01:00
parent 0a77ccf091
commit 9f6fc37a6a
2 changed files with 23 additions and 8 deletions
@@ -165,9 +165,10 @@ public class GenerateToStringWorker {
protected ConflictResolutionPolicy exitsMethodDialog(TemplateResource template) {
final DuplicationPolicy dupPolicy = config.getReplaceDialogInitialOption();
if (dupPolicy == DuplicationPolicy.ASK) {
PsiMethod existingMethod = PsiAdapter.findMethodByName(clazz, template.getTargetMethodName());
String targetMethodName = template.getTargetMethodName(clazz);
PsiMethod existingMethod = targetMethodName != null ? PsiAdapter.findMethodByName(clazz, targetMethodName) : null;
if (existingMethod != null) {
return MethodExistsDialog.showDialog(template.getTargetMethodName());
return MethodExistsDialog.showDialog(targetMethodName);
}
}
else if (dupPolicy == DuplicationPolicy.REPLACE) {
@@ -185,7 +186,9 @@ public class GenerateToStringWorker {
* @param template the template to use
*/
private void beforeCreateToStringMethod(Map<String, String> params, TemplateResource template) {
PsiMethod existingMethod = PsiAdapter.findMethodByName(clazz, template.getTargetMethodName()); // find the existing method
String targetMethodName = template.getTargetMethodName(clazz);
if (targetMethodName == null) return;
PsiMethod existingMethod = PsiAdapter.findMethodByName(clazz, targetMethodName); // find the existing method
if (existingMethod != null && existingMethod.getDocComment() != null) {
PsiDocComment doc = existingMethod.getDocComment();
if (doc != null) {
@@ -15,9 +15,16 @@
*/
package org.jetbrains.java.generate.template;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.java.generate.GenerationUtil;
import org.jetbrains.java.generate.exception.GenerateCodeException;
import java.io.Serializable;
import java.util.Collections;
/**
* A template contains the method body and the filename of the resource where
@@ -193,11 +200,16 @@ public class TemplateResource implements Serializable {
/**
* Gets the method that this template is for (toString)
*/
public String getTargetMethodName() {
String s = getMethodSignature();
s = before(s, "(");
int i = s.lastIndexOf(" ");
return s.substring(i).trim();
public String getTargetMethodName(PsiClass clazz) {
try {
String text = GenerationUtil.velocityGenerateCode(clazz, Collections.emptyList(), Collections.emptyMap(), template, 0, true);
return JavaPsiFacade.getElementFactory(clazz.getProject())
.createMethodFromText(text, clazz, PsiUtil.getLanguageLevel(clazz))
.getName();
}
catch (GenerateCodeException | IncorrectOperationException ignore) {
return null;
}
}
/**