Home > Mobile >  Intellij: Refactor Change Method Signature to change an abstract method from void to Int, but also a
Intellij: Refactor Change Method Signature to change an abstract method from void to Int, but also a

Time:07-20

Long story short personal project of mine, I am trying to re-do the implementation of something. However, there are many uses of this method and it would take me too much time to do it manually.

Using the change method signature window, I can easily change an abstract method of

public abstract void run(int a, int b);

to

public abstract int run(int a, int b);

That part is easy enough and I know how to do it.

However, I'd also like to be add:

Before:

@Override    
public void run(int a, int b) {
   /* irrelevant code here */
}

After:

@Override    
public int run(int a, int b) {
    /* irrelevant code here */
  return -1;
}

Is this possible with any of the tools Intellij has to offer?

CodePudding user response:

Depending on the complexity of your irrelevant code you might be able to get away with using a regex for this.

Something along the lines of:
Find: (\@Override\npublic void run\(int a\, int b\) \{)(.|\n*?)(^})
Replace: $1$2return -1;\n$3


Find explanation:

  • (\@Override\npublic void run\(int a\, int b\) \{) first part of the method
  • (.|\n*?) Find any number of any character (including new lines \n); non greedy (?)
  • (^}) Last/Closing line of the method.
    • Shown here as a line that starts with a closing bracket, but should be changed to match whatever matches the end of your method. Likely four spaces (^\s\s\s\s}) or a tab (^\t})

Replace explanation:

  • $1 first found section
  • $2 second found section
  • return -1;\n new code to add
  • $3 third found section
  • Related