如果我运行重构来提取一个方法,intellij 有时会注意到有类似的代码可以用这个新方法替换。在很多情况下,我的下一步是提取一个参数,现在可以使用这种方法的地方更多了。但是,当我提取参数时,intellij 不会检查是否有新的代码重复项。有办法做到这一点吗?
第一步
package mavensandbox;
public class Main {
public void foo() {
System.out.println("foo");
}
public void bar() {
System.out.println("bar"); //I will extract method for this line
}
}
第二步
package mavensandbox;
public class Main {
public void foo() {
System.out.println("foo");
}
public void bar() {
print();
}
private void print() {
System.out.println("bar"); //doh, I wanted "bar" to be a parameter, that's the next step
}
}
第 3 步
package mavensandbox;
public class Main {
public void foo() {
System.out.println("foo"); //ok, so how do I get intellij to realize it can now call print("foo"); instead?
}
public void bar() {
print("bar");
}
private void print(String s) {
System.out.println(s);
}
}
正如评论所说,我如何让 intellij 意识到它现在可以调用 print("foo");
?
最佳答案
一旦方法被提取出来,IntelliJ 就不够聪明,无法根据提取的参数找出类似的重构。正如您所发现的,它只会将参数提取到提取方法的现有 调用者中。
在您的第 1 步中,尝试通过像这样更改 bar()
来提前设置您的提取方法:
public void bar() {
String s = "bar";
System.out.println(s); // extract method for this line
}
然后在第 2 步中,IntelliJ 已经足够聪明,可以找出所有类似的重构。
如果您因为第一个提取方法重构已经完成并提交而坚持使用第 2 步作为起点,请将我上面所说的应用于 print()
方法(提取方法来自它),你应该能够达到相同的结果。然后,您只需删除剩余的零参数 print()
。
关于java - 有没有办法让Intellij在我刚刚提取参数时用方法替换重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28225880/