简体   繁体   中英

Java enum generics

I have a class as below,

public class Baseclass {
   private final EmployeeEnum empEnum;
   public Baseclass(EmployeeEnum e) {
       this.empEnum = e;
    }
}

Now I want to make the Baseclass generic and make it accept Enums of a certain type.

Since Enum cant extend a class I have created an interface IEnum and made EmployeeEnum and ManagerEnum (the new enum I created) implement the interface.

I have made changes to Baseclass as below,

public class Baseclass {
   private final Enum<?> empEnum;
   public Baseclass(Enum<?> e) {
       this.empEnum = e;
    }
}

Is there a better way to do this?

Cheers!!

If you merely want any enum then you can use E extends Enum<E> .

public class Baseclass<E extends Enum<E>> {

    private final E e;

    public Baseclass(E e) {
        this.e = e;
    }
}

All enum s extend Enum<E> so that they can inherit the standard methods such as name and values . This is one of the reasons why enum s cannot extend other classes because no class in Java is allowed to extend two classes.

Each sub-class must extend BaseClass with a specific enum like this:

enum MyEnum {

    I, Me, My, Mine;
}

class A extends BaseClass<MyEnum> {

    public A(MyEnum e) {
        super(e);
    }

}

If you want further restrictions - such as making subclasses only use enums of a special type (such as implementing an interface) then you can add the interface to the generic like this:

public interface SpecialEnum {

}

enum MyEnum implements SpecialEnum {

    I, Me, My, Mine;
}

enum NotSpecialEnum {

    Am, I, Special;
}

public class BaseClass<E extends Enum<E> & SpecialEnum> {

    private final E e;

    public BaseClass(E e) {
        this.e = e;
    }
}

class A extends BaseClass<MyEnum> {

    public A(MyEnum e) {
        super(e);
    }

}

// This is not allowed.
class B extends BaseClass<NotSpecialEnum> {

    public A(NotSpecialEnum e) {
        super(e);
    }

}

You can even put the enum inside the extending class:

class A extends BaseClass<A.AnotherEnum> {

    enum AnotherEnum implements SpecialEnum {

        Hello, All;
    }

    public A(AnotherEnum e) {
        super(e);
    }

}

Is there a better way to do this?

Better way to do what? You could change to the code below which would limit you to enums that extend IEnum:

class Baseclass<T extends Enum<T> & IEnum> {
    private final T empEnum;
    public Baseclass(T e) {
        empEnum = e;
    }
}

So T extends Enum<T> - T must be an Enum & - and IEnum - T must extend IEnum .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM