Cannot access static field within enum initialiser

前端 未结 5 1443
谎友^
谎友^ 2021-01-07 06:14

In this code I get a compiler error, see comment:

 public enum Type {
   CHANGESET(\"changeset\"),
   NEW_TICKET(\"newticket\"),
   TICKET_CHANGED(\"editedti         


        
5条回答
  •  遥遥无期
    2021-01-07 06:30

    I'd use the Reversible Enum Pattern:

    ReversibleEnum.java

    /**
     * 

    * This interface defines the method that the {@link Enum} implementations * should implement if they want to have the reversible lookup functionality. * i.e. allow the lookup using the code for the {@link Enum} constants. *

    * @author Atif Khan * @param < E > * The value of Enum constant * @param < V > * The Enum constant to return from lookup */ public interface ReversibleEnum< E, V > { /** *

    * Return the value/code of the enum constant. *

    * @return value */ public E getValue(); /** *

    * Get the {@link Enum} constant by looking up the code in the reverse enum * map. *

    * @param E - code * @return V - The enum constant */ public V reverse( E code ); }

    ReverseEnumMap.java

    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 

    * A utility class that provides a reverse map of the {@link Enum} that is keyed * by the value of the {@link Enum} constant. *

    * @author Atif Khan * @param < K > * The class type of the value of the enum constant * @param < V > * The Enum for which the map is being created */ public class ReverseEnumMap< K, V extends ReversibleEnum< K, V >> { private final Map< K, V > mReverseMap = new HashMap< K, V >(); /** *

    * Create a new instance of ReverseEnumMap. *

    * @param valueType */ public ReverseEnumMap( final Class< V > valueType ) { for( final V v : valueType.getEnumConstants() ) { mReverseMap.put( v.getValue(), v ); } } /** *

    * Perform the reverse lookup for the given enum value and return the enum * constant. *

    * @param enumValue * @return enum constant */ public V get( final K enumValue ) { return mReverseMap.get( enumValue ); } }

    You'd change Type.java as follows:

    public enum Type implements ReversibleEnum< String, Type >  {
      CHANGESET( "changeset" ),
      NEW_TICKET( "new" ),
      TICKET_CHANGED( "changed" ),
      CLOSED_TICKET( "closed" );
    
      private String mValue;  
    
      private static final ReverseEnumMap< String, Type > mReverseMap = new ReverseEnumMap< String, Type >( Type.class );  
    
      Type(final String value)   
      {  
        mValue = value;  
      }  
    
      public final String getValue()   
      {  
        return mValue;  
      }  
    
      public Type reverse( final String value )  
      {  
        return mReverseMap.get( value );  
      } 
    } 
    

提交回复
热议问题