How to extend static methods for enums implementing an interface?

我的未来我决定 提交于 2019-12-11 07:17:32

问题


This question is closely related to my previous question on SO about using interface with enums. Essentially, I have a bunch of enums that are closely related, and they all implement a common interface.

The interface is called Sections and the enums are called SectionA, SectionB, etc. I have other classes which have fields like List<Sections> and Map<Sections, String>. Now, to populate these fields, I would like to have access to valueOf(String), i.e. I would like to be able to say something like

Map<Sections, String> sectionsMap = new HashMap<Sections, String>();
for (String s : someStringList) {
    try {
        sectionsMap.put(Sections.valueOf(s), someOtherFunctionReturningString(s));
    } catch (IllegalArgumentException e) {
        e.printStackTrace(); // if s doesn't match any enum
    }
}

I also have my own static methods in the enums SectionA, SectionB, etc. (This is because these enums all have a single java.util.regex.Pattern field, and my static method is a generalization of the valueOf(String) method based on pattern matching.)

So, my question is this:

How can I retain access to the static methods of these enums while also having their generalization at the interface level?

I am open to other design decisions (in fact, I am currently getting rid of the whole enum idea and creating classes that implement Sections and extend an abstract class AbstractSection), but I am quite curious about how others make their decisions in similar situations. I have asked this question with the hope that someone out there has better ideas than those in my head.


回答1:


You cannot override an static method. A subclass may name a static method the same as that of the superclass, however super is a non-static operator. You could have multiple methods which perform two different functions, but they would need different names.



来源:https://stackoverflow.com/questions/21789191/how-to-extend-static-methods-for-enums-implementing-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!