简体   繁体   中英

Is there a way to refactor by adding an outer method call using Intellij?

I have this:

Arrays.asList(from(A, 14), from(A, 21), ...

What I need is:

Arrays.asList(of(from(A, 14), 1), of(from(A, 21), 2), ...

The call from(A, number) should be turned into of(from(A, number), anotherNumber) .

In other words: I have to update a lengthy list of such from() calls by enclosing them within an of() and adding a second parameter. Ideally, that second parameter would simply count upwards.

Is there a way to that with IntelliJ refactoring tools? ( instead of doing it all manually )

And note: I am not asking for a tools recommendation. I am asking whether a known tool supports a specific refactoring situation.

You can highlight from( and use the "select next occurrence" hot key. Once you have selected all occurrences just replace it with of(from . Once you are done adding of you can use the "alt + left arrow key" to move the cursor to the position where you want to add the number OR use the "select next occurrence" by highlighting the ), .

On Mac the hot key is "CTRL + G" and on Windows\\Linux "ALT + J". Here is a list of the hot keys https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf

It is still a bit manual, but beats doing it one by one.

You can try the following:

  • Extract method with replacing the duplicates for from(A, param)
  • Inside the extracted method write something like of(from(A, param), NNN)
  • Inline method
  • Replace NNN with numbers you need (this has to be performed manually)

If there is some formula that can calculate anotherNumber based on number , you can use it instead of NNN .

"Replace structurally" can do some of what you need.

  1. Select Edit > Find > Replace Structurally...
  2. Enter from($a$, $b$) as the search template
  3. Enter of(from($a$, $b$), i) as the replacement template
  4. Choose Scope : Current File (or Selection , if you prefer)
  5. Hit Find
  6. Hit Replace all

Assuming i is undefined you'll then be left with lots of errors. You can cycle through the errors with F2 and replace the undefined i with the values you want.


Bonus tip: on a Mac, run seq 1 100 | pbcopy seq 1 100 | pbcopy at a terminal to put the numbers 1-100 into your clipboard. Then, with multiple cursors in IntelliJ, hit Paste. 1 will be pasted at the first cursor, 2 at the second, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM