Tyler Durden
Tyler Durden

Reputation: 11532

Refer to value of enum itself in static method of an enum

I have a Java enum with a static method and I want to refer to the value of the enum in the method:

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

So, for example, I want to call convert like follows:

SpeedUnits eMySpeedUnit = SpeedUnits.feetpersecond;
int knots = eMySpeedUnit.convertToIntegerKnots( 80 );

How do I refer to the current value of the enum variable within the static method (see *** places in code above) ?

Upvotes: 1

Views: 1293

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

In your example, you invoke the convertToIntegerKnots method on an instance of SpeedUnits. And the behavior of the method depends on this instance. So the method should simply not be static, and you can refer to the instance on which the method is called using this:

public int convertToIntegerKnots( int value ){
    if( this == knots) return value;
    if( this == feetpersecond ) return (int)( value * 0.592483801295896 );
}

But it would be much cleaner to define the method as an abstract method, and to override it in every enum instance, exactly as you did with the getAbbreviation() method.

Upvotes: 4

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15497

There is no current value of the enum in a static method. After you make it non-static you can use this to refer to the current value.

Upvotes: 2

Related Questions