Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference enum items generally in java

I have an enum class like this:

public enum EArea 
{
    DIRECTLANE,
    TURNLEFTLANE,
    INTERSECTION,
    SIDEWALK,
    FORBIDDEN;
}

I would like to build an AtomicRefrence from a value of this enum in another class:

public class CArea<T extends Enum<?>>
{
    private final AtomicReference<T> type;

    public CArea( ... ) //what should I put here?
    {
        type = new AtomicReference<T>( ... ); // and here?
    }
} 

I want to do later:

CArea area1 = new CArea( EArea.SIDEWALK );
CArea area2 = new CArea( EArea.DIRECTLANE );

But I don't know how can I reference items of an enum in a method generally (here constructor).

like image 709
Ehsan Avatar asked Feb 09 '26 20:02

Ehsan


1 Answers

As mentioned in the comments, you can pass the Enum value (an instance) to the constructor.

public class CArea<T extends Enum<T>>
{
    private final AtomicReference<T> type;

    public CArea(T enumVal)
    {
        type = new AtomicReference<>(enumVal);
    }
} 

CArea area1 = new CArea<>(EArea.SIDEWALK);
CArea area2 = new CArea<>(EArea.DIRECTLANE);

Note: With this the type parameter could be any enum.

like image 109
user7 Avatar answered Feb 12 '26 14:02

user7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!