gpt4 book ai didi

java - Eclipse 中的默认导入

转载 作者:搜寻专家 更新时间:2023-10-30 19:41:34 25 4
gpt4 key购买 nike

有没有办法在 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 在重构和创建新实体时非常缺乏代码生成的可定制性。

您可能想查看 Eclipse Optimize Imports to Include Static Imports有关如何使内容辅助在预定义类中查找静态方法的信息。这可能是你真正想要的。在接受的答案中,Joey Gibson 写道,您可以将 org.hamcrest.Matchers 添加到 Window » Preferences » Java » Editor » Content Assist » Favorites


针对静态导入 Hamcrest 方法的特定问题的另一种解决方案是配置一个名为 hamcrest 的代码模板。这样你就可以简单地输入 ham 并跟进 ctrl + space 在顶部获取导入。

模板应该是这样的

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

一个更方便的 hack 是将这个模板添加到已经存在的 test 代码模板中,它会生成一个新的测试方法。如果您将此模板更改为:

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

每次您创建新的测试方法时都使用它,您将永远不必担心再次手动添加 hamcrest 导入。

显示配置位置的图像: hamcrest code template

关于java - Eclipse 中的默认导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28582625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com