你知道怎么用Idea抽取方法、创建class吗?

时间:2024-01-01 14:51:45

liJ IDEA的快捷键是进行重构的利器,坊间盛传,完全使用IDEA快捷键重构的代码,是不需要写测试用例保护的

本文就分享一个使用IDEA抽取方法及创建新的class的方法

工具/原料

  • IntelliJ IDEA

方法/步骤

  1. 先来一段需要重构的代码:

    package chapter4;import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.List;

    /**

    * Created by MyWorld on 2016/3/21.

    */

    public class RefactorOperate {

    public static void main(String[] args) {

    List<String> seasonList = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Autumn", "Winter"));

    for (String season : seasonList) {

    System.out.println(season);

    }

    seasonList.add("Spring Rain");

    seasonList.add("vernal equinox");

    System.out.println("======================");

    for (String season : seasonList) {

    System.out.println(season);

    }

    }

    }

    你知道怎么用Idea抽取方法、创建class吗?
  2. 先把重复的代码中负责打印操作的代码提到一个方法中

    操作:

    如下截图所示,选中需要提取的代码

    同时Ctrl+Alt+m

    在弹出的对话框中,填入将要新生成的方法的名字,此处我们取的方法名是print

    最后点“确定”

    你知道怎么用Idea抽取方法、创建class吗?
  3. 现在马上就可以看到 IDEA的一个方便、强大的功能了

    从自动检测出类似代码,并提示出来

    "IDEA has detected 1 code fragment in this file that can be replaced with a call  to extracted method. would you like to review and replace it "

    此处我们选“Yes”

    你知道怎么用Idea抽取方法、创建class吗?
  4. 看看抽取方法后,现在代码的情况:

    package chapter4;import java.util.ArrayList;

    import java.util.Arrays;

    import java.util.List;

    /**

    * Created by MyWorld on 2016/3/21.

    */

    public class RefactorOperate {

    public static void main(String[] args) {

    List<String> seasonList = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Autumn", "Winter"));

    print(seasonList);

    seasonList.add("Spring Rain");

    seasonList.add("vernal equinox");

    System.out.println("======================");

    print(seasonList);

    }    private static void print(List<String> seasonList) {

    for (String season : seasonList) {

    System.out.println(season);

    }

    }

    }

    你知道怎么用Idea抽取方法、创建class吗?
  5. 输入“StringUtils utils=new StringUtils();”

    IDEA肯定会提示编译不过。肯定不过了,因为Project中根本没有这个class

    把鼠标放在报错代码上,同时按“Alt + Enter”

    在弹出的菜单中选中“Create Class 'StringUtils'”

    然后回车(当然,使用鼠标直接点击也可以)

    你知道怎么用Idea抽取方法、创建class吗?
  6. 在弹出的“Create Class StringUtils”对话框中,确认下Destination Package的位置

    此处,我们就话在这个package下,直接点“OK”

    新Class StringUtils就创建完成了!!

    你知道怎么用Idea抽取方法、创建class吗?
    你知道怎么用Idea抽取方法、创建class吗?