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); } }}
2、先把重复的代码中负责打印操作的代码提到一个方法中操作:如下截图所示,选中需要提取的代码同时Ctrl+Alt+m在弹出的对话框中,填入将要新生成的方法的名字,此处我们取的方法名是print最后点“确定”
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”
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); } }}
5、输入“StringUtils utils=new StringUtils();”IDEA肯定会提示编译不过。肯定不过了,因为Project中根本没有这个class把鼠标放在报错代码上,同时按“Alt + Enter”在弹出的菜单中选中“Create Class 'StringUtils'”然后回车(当然,使用鼠标直接点击也可以)
6、在弹出的“Create Class StringUtils”对话框中,确认下Destination Package的位置此处,我们就话在这个package下,直接点“OK”新Class StringUtils就创建完成了!!