简体   繁体   中英

Java generic Enum

For my icons in Swing i've different enums like:

    public enum Icon32 {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
    private File path;

    private Icon32(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }

or

public enum Tab {
    XML("resources/icons/x32/tab/tab_1.ico"), QR("resources/icons/x32/tab/tab_2.ico"),ABOUT("resources/icons/x32/tab/tab_3.ico");
    private File path;

    private Tab(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }

}

I've created an abstract implementation:

public abstract class AbstractImageType {

private File path;

private AbstractImageType(String path) {
    this.path = new File(path);
}

public File getFile() {
    return path;
}

@Override
public String toString() {
    return path.toString();
}

}

But Enum is not possible to extend:

Syntax error on token "extends", implements expected

Now my question, is it possible to make a generic class "AbstractImageType" whos implementing the method(s) and constructor? so i've only to insert the Enum values?

Something like this:

 public enum Icon32 extends AbstractImageType {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
}

Enums in java do not support inheritence from classes because each enum is actually a simple class that extends Enum . Since multiple inheritance is not supported you cannot create base class for 2 enums.

You can either stop using enums for this purpose, ie switch to regular classes or use delegation to create File, ie utility that accepts enum member and returns File instance.

You can make your AbstractImageType an interface and have your enums implement that.

public interface AbstractImageType {

    File getFile();
}

public enum Icon32 implements AbstractImageType  {
    STOP("resources/icons/x32/stop.ico"),
    RUN("resources/icons/x32/run.ico");
    private File path;

    private Icon32(String path) {
        this.path = new File(path);
    }

    public File getFile() {
        return path;
    }
}

Unfortunately, it's not possible to use any kind of inheritance for enums, since it would break the Liskov Substitution Principle . Java 8 will have default implementations of methods in interfaces, but they probably won't extend to constructors.

The best you can do is probably to generate the code, such as with custom templates in eclipse.

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