如何扩展实现接口的枚举的静态方法? [英] How to extend static methods for enums implementing an interface?

查看:232
本文介绍了如何扩展实现接口的枚举的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与我之前关于使用与枚举使用界面的问题有密切关系。基本上,我有一堆密切相关的枚举,它们都实现了一个通用的界面。

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.

界面称为 Sections 和枚举被称为 SectionA SectionB 等。我有其他类有类似列表< Sections> Map< Sections,String> 。现在,要填充这些字段,我想访问 valueOf(String),即我想能够说出像

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
    }
}

我也有我自己的静态方法在枚举 SectionA SectionB 等(这是因为这些枚举都有一个单个 java.util.regex.Pattern 字段,我的静态方法是对 valueOf(String)方法的一般化基于模式匹配。)

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:

我如何保留访问这些枚举的静态方法,同时也在界面级别进行泛化?

我对其他设计决定(其实我是目前正在摆脱整个枚举的想法,并创建实现 Sections 的类,并扩展一个抽象类 AbstractSection ),但我很好奇他人如何在类似的情况下做出决定。我已经问过这个问题,希望有一个人比我头脑里有更好的想法。

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.

推荐答案

你不能覆盖静态方法。
子类可以命名与超类相同的静态方法,但是 super 是一个非静态运算符。
你可以有多个方法执行两个不同的功能,但是它们需要不同的名字。

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.

这篇关于如何扩展实现接口的枚举的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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