简体   繁体   English

我如何重构对静态枚举成员的引用

[英]How do I re-factor references to static enum members

My code consists of references to enumeration in the following fashion. 我的代码包含以下列方式引用枚举的方法。

Flowers { ROSE, SUNFLOWER }

import com.mycompany.Flowers;

class A {
    public void foo(...) {
        Flowers flower = Flowers.ROSE;
    }
}

I would like the above code to use static references to Flowers, the code would then look like 我希望上面的代码使用对Flowers的静态引用,然后代码看起来像

import static com.mycompany.Flowers.ROSE;

Flowers flower = ROSE;

How can I re-factor my code (using Eclipse) to use static references of enums instead of the normal referencing mechanism. 我如何重构我的代码(使用Eclipse)以使用枚举的静态引用代替常规的引用机制。 Is there a way to tell Eclipse to modify all regular enum references to static references? 有没有办法告诉Eclipse将所有常规枚举引用修改为静态引用?

That's probably not as proficient as you're looking for, but Ctrl + Shift + M on the reference of a static object will statically import it (works for members and methods alike)... That way you can achieve your static imports one-by-one. 这可能不像您想要的那样熟练,但是对静态对象的引用按Ctrl + Shift + M可以将其静态导入(适用于成员和方法)...这样一来,您可以实现静态导入-一一。

I'm interested too in other ideas, though 我对其他想法也很感兴趣

Here's how you can do it in two simple steps: 您可以通过以下两个简单步骤来完成此操作:

  • Use a find and replace maybe with a regular expression to change all the instances Flowers.NAME to just NAME . 使用查找并用正则表达式替换可以将所有实例Flowers.NAME更改为NAME
  • Then do a project wide 'Organize imports' like so: Select the project in the package explorer and press Ctrl + Shift + O (same keystroke as the single class version). 然后像这样在整个项目范围内进行“组织导入”:在包资源管理器中选择项目,然后按Ctrl + Shift + O (与单个类版本的击键相同)。 Should work for packages, etc.. Bobs your uncle. 应该工作包,等等。鲍勃你的叔叔。 (From this answer ). (来自此答案 )。

只需在单词Rose按Ctrl + Shift + M ,您将看到它是静态导入的。

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

相关问题 有没有办法编码重要因子交换整数 - Is there a way to code re-factor swapping integers 如何使用静态成员泛化Java枚举? - How to genericize a Java enum with static members? 如何在 Java 中获取 static class 成员的枚举? - How to get an enum of static class members in Java? 如何在 Java 中按字母顺序对枚举成员进行排序? - How do I sort enum members alphabetically in Java? 当嵌套的Enum在其构造函数中引用父静态成员时,为什么会得到NPE? - Why do I get an NPE when a nested Enum references a parent static member in its constructor? 如何处理意图内的非静态成员? - How do I deal with non-static members inside of an intent? 如何从静态上下文引用枚举变量? - How do I reference an enum variable from a static context? 当它们作为 lambdas 或方法引用传递时,如何实现可移除的侦听器? - How do I implement removeable listeners when they're passed as lambdas or method references? 我何时/如何初始化抽象类的静态成员? (没有延迟加载) - When/how do i initialize static members of an abstract class ? (no lazy loading) 为什么我不能从Java中的专用枚举值访问静态最终成员 - Why can't I access static final members from a dedicated enum value in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM