有没有办法自定义Eclipse中的默认导入?
例如,如果我默认打开一个新的JUnit测试类,则会得到以下导入:
import static org.junit.Assert.*;
import org.junit.Test;
我想要得到什么:
import static org.junit.Assert.*;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
最佳答案
不幸的是,在重构和创建新实体时,Eclipse完全缺乏代码生成的可定制性。
您可能想 checkout Eclipse Optimize Imports to Include Static Imports以获取有关如何使内容帮助在预定义类中查找静态方法的信息。那可能就是您真正想要的。在接受的答案中,Joey Gibson写道,您可以将org.hamcrest.Matchers
添加到窗口»首选项»Java»编辑器»内容助手» Collection 夹。
解决静态导入Hamcrest方法的特定问题的另一种解决方案是配置一个名为hamcrest的代码模板。这样,您只需键入ham并按ctrl +空格跟随即可将导入置于顶部。
模板应该看起来像
${staticImport:importStatic('org.hamcrest.Matchers.*')}${cursor}
一个更方便的技巧是将该模板添加到已经存在的
test
代码模板中,该模板会生成新的测试方法。如果将此模板更改为:@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
${staticImport1:importStatic('org.hamcrest.Matchers.*')}
${staticImport2:importStatic('org.junit.Assert.*')}${cursor}
}
并在每次使用新的测试方法时都使用它,您将不必再担心手动添加hamcrest导入。
显示配置位置的图像: