PsiMethod (PsiClass clazz, @NotNull PsiMethod newMethod, Editor editor) { // if main method exists and is the last then add toString just before main method PsiMethod mainMethod = PsiAdapter.findPublicStaticVoidMainMethod(clazz); if (mainMethod != null) { // add before main method if it is the last method PsiMethod[] methods = clazz.getMethods(); if (mainMethod.equals(methods[methods.length - 1])) { return (PsiMethod) clazz.addBefore(newMethod, mainMethod); // return as the method is added } } // otherwise add it at the end PsiElement last = clazz.getRBrace(); // rbrace is the last }