我有一个带有静态方法的 Java 枚举,我想在方法中引用枚举的值:
public enum SpeedUnits {
knots { @Override public String getAbbreviation(){ return "kts"; } },
feetpersecond { @Override public String getAbbreviation(){ return "fps"; } };
public abstract String getAbbreviation();
public static SpeedUnits forAbbreviation( String sAbbreviation ){
if( sAbbreviation == null ) return null;
if( sAbbreviation.equalsIgnoreCase( "kts" ) ) return knots;
if( sAbbreviation.equalsIgnoreCase( "fps" ) ) return feetpersecond;
return null;
}
public static int convertToIntegerKnots( int value ){
if( *** speed-type-goes-here *** == knots) return value;
if( *** speed-type-goes-here *** == feetpersecond ) return (int)( value * 0.592483801295896 );
}
}
所以,例如,我想像下面这样调用转换:
SpeedUnits eMySpeedUnit = SpeedUnits.feetpersecond;
int knots = eMySpeedUnit.convertToIntegerKnots( 80 );
如何在静态方法中引用枚举变量的当前值(参见上面代码中的 *** 位置)?
最佳答案
在您的示例中,您在 SpeedUnits 的实例
上调用了 convertToIntegerKnots 方法。并且该方法的行为取决于此实例。所以该方法不应该是静态的,您可以使用 this
引用调用该方法的实例:
public int convertToIntegerKnots( int value ){
if( this == knots) return value;
if( this == feetpersecond ) return (int)( value * 0.592483801295896 );
}
但是将方法定义为抽象方法并在每个枚举实例中重写它会更简洁,就像您对 getAbbreviation()
方法所做的那样。
关于java - 在枚举的静态方法中引用枚举本身的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27387031/