Eclipse中的默认导入 [英] Default imports in Eclipse

查看:32
本文介绍了Eclipse中的默认导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Eclipse中自定义默认导入?

Is there a way to customize the default imports in Eclipse?

例如,如果我默认情况下打开一个新的JUnit测试类,则会得到以下导入:

For example if I open a new JUnit Test Class by default I get these imports:

import static org.junit.Assert.*;
import org.junit.Test;

我想要得到的东西:

import static org.junit.Assert.*;
import org.junit.Test;
import static org.hamcrest.Matchers.*;

推荐答案

不幸的是,在重构和创建新实体时,Eclipse缺乏代码生成的可定制性.

Unfortunately, Eclipse is quite lacking in the customizability of code generation when refactoring and creating new entities.

您可能想查看 Eclipse优化导入以包括静态导入有关如何使内容辅助的信息,请在预定义的类中找到静态方法.那可能就是您真正想要的.在接受的答案中,乔伊·吉布森(Joey Gibson)写道,您可以将 org.hamcrest.Matchers 添加到窗口»首选项»Java»编辑器»内容助手»收藏夹.

You might want to check out Eclipse Optimize Imports to Include Static Imports for information how to make content assist find static methods in predefined classes. That might be what you actually want. In the accepted answer Joey Gibson writes that you can add org.hamcrest.Matchers to Window » Preferences » Java » Editor » Content Assist » Favorites.

静态导入Hamcrest方法的特定问题的另一种解决方案是改为配置名为hamcrest的代码模板.这样,您只需键入 ham ,然后跟随 ctrl + space 即可将导入操作置于顶部.

Another solution to the specific problem of statically importing Hamcrest methods, is to configure a Code Template named hamcrest instead. That way you can simply type ham and follow up with ctrl + space to get the import at the top.

模板应该看起来像

${staticImport:importStatic('org.hamcrest.Matchers.*')}${cursor}

一个更方便的技巧是将此模板添加到已经存在的 test 代码模板中,从而生成新的测试方法.如果您将此模板更改为:

An even more convenient hack is to add this template to the already existing test code template which generates a new test method. If you change this template to:

@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
    ${staticImport1:importStatic('org.hamcrest.Matchers.*')}
    ${staticImport2:importStatic('org.junit.Assert.*')}${cursor}
}

并在每次使用新的测试方法时都使用它,您将不必在乎再次手动添加hamcrest导入.

and use this each time you make a new test method you will never have to care about adding the hamcrest import manually again.

图片以显示您在哪里配置它:

Image to show where you configure it:

这篇关于Eclipse中的默认导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆