在IntelliJ下使用instance method替换static method

本文介绍了如何在IntelliJ IDEA环境下将静态方法转换为实例方法。通过手动步骤和使用IDE的内置重构工具,详细展示了两种转换方法,旨在帮助开发者理解并实践代码重构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家都知道在绝大多数情况下,我们都不应该是用static方法。但如果真的有了,比如说是在遗留系统中有这样的代码,我们应该怎么样“安全”的重构呢?

给一个简单的例子,假设我们有一个类叫做MyMath,代码如下:

MyMathTest.java

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(MyMath.add(1, 1), is(2));
    }
}

MyMath.java

public class MyMath {
    public static int add(int a, int b) {
        return a + b;
    }
}


方法一:手动替换

1.拷贝static方法的body到另一个临时方法里

MyMath.java
public class MyMath {
    public static int add(int a, int b) {
        return a + b;
    }

    public int add2(int a, int b) {
        return a + b;
    }
}

2.delegate方法调用

public static int add(int a, int b) {
        return new MyMath().add2(a, b);
}

3. inline static方法

public class MyMath {

    public int add2(int a, int b) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(new MyMath().add2(1, 1), is(2));
    }
}

这样就达到了替换的目的。

4. 重命名add2到add,完


方法二:intellij的convert to instance method

1.改变方法签名(Command/Ctrl + F6),传入一个MyMath的instance

public class MyMath {
    public static int add(int a, int b, MyMath myMath) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(MyMath.add(1, 1, new MyMath()), is(2));
    }
}

2.使用intellij的convert to instance method

选中add,然后在refactor中选中convert to instance method。


在弹出的窗口中选择instance parameter为myMath。


然后就大工告成:

public class MyMath {
    public int add(int a, int b) {
        return a + b;
    }
}

public class MyMathTest {
    @Test
    public void shouldReturnSumOfTwoNumbersWhenAdd() {
        assertThat(new MyMath().add(1, 1), is(2));
    }
}


总结:

在开始学重构的时候,最好是从手动重构开始,包括最简单的提取方法这些,都最好从手动开始,到后面,你重复了足够次数以后,尽量采用IntelliJ的自动重构来进行重构

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值