How can I apply the “move method” refactoring with IntelliJ IDEA?

前端 未结 5 858
感情败类
感情败类 2021-02-01 17:53

I want to be able to move an instance method from one class to another class (\"Move method\" from Fowler\'s \"Refactoring\") in IntelliJ IDEA. Unfortunately, when I try \"Move.

5条回答
  •  没有蜡笔的小新
    2021-02-01 18:12

    There is another method. Imagine you have the code:

    public int field;
    
    public void foo(int a) {
        assert field == a;
    }
    

    And you want to make foo static. Select the whole body of the method and preess Alt+Ctrl+M (Extract method). Type the same name of the method. Check "Declare static" checkbox (available only if the method only reads and doesn't modify the fields) and press Ok. So you get:

    public void foo(int a) {
        foo(a, field);
    }
    
    private static void foo(int a, int field) {
        assert field == a;
    }
    

    Move static method wherever you want and use old foo's body to call it.

提交回复
热议问题