IntelliJ IDEA的快捷键是进行重构的利器。
坊间盛传,完全使用IDEA快捷键重构的代码,是不需要写测试用例保护的
上面已经介绍过此类操作。
本文和上文起的作用相同,只是手法上不同
前期准备工作(包括相关工具或所使用的原料等)IntelliJ IDEAjava 详细的操作方法或具体步骤
先来看看代码:
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
StringUtils stringUtils=new StringUtils();
print(seasonList,stringUtils);
seasonList.add("Spring Rain");
seasonList.add("vernal equinox");
System.out.println("======================");
print(seasonList, stringUtils);
} public static void print(List
for (String season : seasonList) {
System.out.println(season);
}
}
}
package chapter4;
/**
* Created by MyWorld on 2016/3/22.
*/
public class StringUtils {
}


去掉要移动到另外class中的print前面的static关键字
remove static修饰关键字的Code:
public void print(List
for (String season : seasonList) {
System.out.println(season);
}
}

在print方法名或print方法块内的任一位置,按F6
会弹出“Move instance parameter”的对话框
是不是和上一篇分享中弹出的“Move Members”对话框不同,这也是去掉static关键字的原因。

在“Move instance parameter”对话框中,可以看到已经选中“StringUtils”这个实例,也就是会把print方法移到StringUtils这个class中
点击“Refactor”按钮

看看结果:
public class RefactorOperate {
public static void main(String[] args) {
List
StringUtils stringUtils=new StringUtils();
stringUtils.print(seasonList);
seasonList.add("Spring Rain");
seasonList.add("vernal equinox");
System.out.println("======================");
stringUtils.print(seasonList);
}
}
public class StringUtils {
public void print(List
for (String season : seasonList) {
System.out.println(season);
}
}
}


把print方法移动到StringUtils中的目标已经实现。
现在来清清场:
print方法以前是静态的,作为工具类。move后仍应为static,不能更改之前代码的行为特征
给StringUtils的print方法增加static修饰关键字
在RefactorOperate的main方法使用print方法的语句上,同时按Alt+Enter
在弹出的对话框中选“Add static import for 'chapter4.StringUtils.print'”
回车

在main方法的stringUtils变量上同时按Alt+Enter键
在弹出的菜单中选”Remove variable 'stringUtils'
回车
在弹出的对话框中,点击”Remove“按钮
因为这个变量never be used


看看最后的代码:
public class RefactorOperate { public static void main(String[] args) {
List
StringUtils.print(seasonList);
seasonList.add("Spring Rain");
seasonList.add("vernal equinox");
System.out.println("======================");
StringUtils.print(seasonList);
}
}
public class StringUtils {
public static void print(List
for (String season : seasonList) {
System.out.println(season);
}
}
}


分析下这种手法的原理:
StringUtils stringUtils=new StringUtils();
print(seasonList,stringUtils);
上面两行代码,移动后,变为
StringUtils stringUtils=new StringUtils();
stringUtils.print(seasonList);
上面这两种代码的写法是等价的
经验内容仅供参考,如果您需解决具体问题(尤其法律、医学等领域),建议您详细咨询相关领域专业人士。作者声明:本教程系本人依照真实经历原创,未经许可,谢绝转载。- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
