如何为几个Java枚举添加常用方法?(抽象类祖先?
2022-09-04 07:05:52
我有一些这样的Java枚举
public enum Aggregation
{
MORTGAGE( "Mortgage" ),
POOLS( "Pools" ),
PORTFOLIO( "Portfolio" );
private Aggregation( final String name )
{
m_Name = name;
}
private String m_Name;
static Map< String, Aggregation > c_LOOKUP =
new HashMap< String, Aggregation >();
static {
for (Aggregation agg:values()){
c_LOOKUP.put(agg.m_Name,agg);
}
}
public Aggregation lookup(String name){
return c_LOOKUP.get( name );
}
@Override
public String toString()
{
return m_Name;
}
}
public enum Interval
{
MONTHLY( "Monthly" ),
QUARTLY( "Quartly" ),
SEMIANNUALLY( "SemiAnnually" ),
ANNUALLY("Annually");
private Interval( final String name )
{
m_Name = name;
}
private String m_Name;
static Map< String, Interval > c_LOOKUP =
new HashMap< String, Interval >();
static {
for (Interval agg:values()){
c_LOOKUP.put(agg.m_Name,agg);
}
}
public Interval lookup(String name){
return c_LOOKUP.get( name );
}
@Override
public String toString()
{
return m_Name;
}
}
如您所见,这里有很多代码重复。如果有一种方法可以引入像抽象的共同祖先类这样的东西,那就太好了。但是java枚举不能固有。最好的方法是什么?谢谢。
编辑:我制定了一个类似于ŁukaszBachman和missingfacktor的版本
static public enum Aggregation
{
MORTGAGE( "Mortgage" ),
POOLS( "Pools" ),
PORTFOLIO( "Portfolio" );
private final String m_Name;
final static private ReverseDictionary< Aggregation > c_DICTIONARY =
new ReverseDictionary< Aggregation >( Aggregation.class );
static public Aggregation lookup( final String name )
{
return c_DICTIONARY.lookup( name );
}
private Aggregation( final String name )
{
m_Name = name;
}
@Override
public String toString()
{
return m_Name;
}
}
static public enum Interval
{
MONTHLY( "Monthly" ),
QUARTLY( "Quartly" ),
SEMIANNUALLY( "SemiAnnually" ),
ANNUALLY( "Annually" );
private final String m_Name;
final static private ReverseDictionary< Interval > c_DICTIONARY =
new ReverseDictionary< Interval >( Interval.class );
static public Interval lookup( final String name )
{
return c_DICTIONARY.lookup( name );
}
private Interval( final String name )
{
m_Name = name;
}
@Override
public String toString()
{
return m_Name;
}
}
static public class ReverseDictionary< E extends Enum< E >>
{
Map< String, E > c_LOOKUP = new HashMap< String, E >();
public ReverseDictionary( final Class< E > enumClass )
{
for( final E agg : EnumSet.allOf( enumClass ) )
{
c_LOOKUP.put( agg.toString(), agg );
}
}
public E lookup( final String name )
{
return c_LOOKUP.get( name );
}
}
我看到了一些推理。但是,它仍然不是很令人满意。
- 由于返回类型不同,很难定义接口
lookup(String)
- 我可以理解它不是真正的重复,而是一个规范,但我仍然觉得m_Name字段和toString()逻辑有点多余。我们实际上是在指定一类枚举,在我看来,这似乎是“is-a”关系。
lookup(String)