简体   繁体   English

在eclipse中内联所有静态导入

[英]Inline all static imports in eclipse

I was cleaning up some code and happened upon com.example.StringHelper that contained 6 or 7 public static methods (for example concatStrings(String...) , but no member fields. There were a number of classes subclassing this class just so they could call concatStrings(str1, str2) without prefixing it with the class like so: StringHelper.concatStrings(str1, str2) . 我正在清理一些代码并发生在com.example.StringHelper ,它包含6或7个public static方法(例如concatStrings(String...) ,但没有成员字段。有许多类concatStrings(String...)这个类只是为了它们可以调用concatStrings(str1, str2)而不用像这样的类前缀: StringHelper.concatStrings(str1, str2)

I didn't want them subclassing a class just for that reason, so I broke a bunch off. 我不希望他们因为这个原因而继承类,所以我打破了一堆。 I pasted the following static import into the top of any file subclassing it after removing the extends StringHelper : 在删除extends StringHelper之后,我将以下静态导入粘贴到任何extends StringHelper它的文件的顶部:

import static com.example.StringHelper.*;

Eclipse simplified this into specific imports for only the methods being used. Eclipse将其简化为仅针对所使用方法的特定导入。

Question : Is there a simple way to have Eclipse "inline" these static imports? 问题 :有没有一种简单的方法让Eclipse“内联”这些静态导入? Can I get it to remove the actual static import and prefix every call with StringHelper. 我是否可以通过StringHelper.删除实际的静态导入和前缀StringHelper. instead? 代替?

Note This is a simplified contrived example, so please don't complain about why we need a StringHelper in the first place. 注意这是一个简化的人为例子,所以请不要抱怨为什么我们首先需要一个StringHelper。

This will do it: 这样做:

  • Highlight one invocation of concatStrings(). 突出显示concatStrings()的一次调用。 Make sure to include the parentheses in the highlighting. 确保在突出显示中包括括号。 Select Refactor/Extract Method, call it foo. 选择Refactor / Extract Method,将其命名为foo。 Make sure to check the "Replace 47 additional occurrences of statements with method" 一定要检查“用方法替换47个附加的语句”
  • In your new foo method, add the "StringHelper." 在新的foo方法中,添加“StringHelper”。 prefix to the invocation of concatStrings 调用concatStrings的前缀
  • remove the import static 删除导入静态
  • Do Refactor/Inline to get rid of foo and put your static calls back where they belong, along with their shiny new Prefixes. Do Refactor / Inline可以摆脱foo并将静态调用放回到它们所属的位置,以及它们闪亮的新前缀。

Don't know if there's an automatic way, but I think it can help in a manual way. 不知道是否有自动方式,但我认为它可以以手动方式提供帮助。 Delete the import, then click on each line with an error on it. 删除导入,然后单击每行并显示错误。 Press ctrl-1 for 'quick fix' and choose the quick fix that prefixes the package name rather than add an import. 按ctrl-1进行“快速修复”,然后选择前缀包名称的快速修复,而不是添加导入。

Preferences -> Java -> Code Style -> Organize Imports

在那里,您可以配置将它们分组所需的导入数量。

Preferences > Java > Code Style > Organize Imports: 首选项> Java>代码样式>组织导入:

"Number of static imports needed for .*" set this to 1. “。*所需的静态导入数”将此值设置为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM