简体   繁体   中英

Java casting enum to a class

I have a class which is identical to enum. The only difference is that I create the class so that I can dynamically create the enums. What I want is to override the cast operation of enum so that I can give the enum instance to a method where it gets the class instance.

Example:

public enum SpecialEnum {
    FIRST("First"), SECOND("Second");

    private String name;

    SpecialEnum(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class SpecialClass {
    private String name;

    public SpecialClass(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public void displayName(SpecialClass specialClass) {
    System.out.println(specialClass.getName());
}

Lets say that the SpecialClass instances are coming from a server where I display them. But I also want to use my pre-defined Special enum classes as well. I know that I could create static instances of SpecialClass and use them but not that it looks messy, also using enums are beneficial to my occasion as well. Is there a way to override casting operation of the enum class of a work around maybe?

Extract an interface :

public interface Named {
    public String getName();
}

public class SpecialClass implements Named {
    private String name;

    public SpecialClass(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

public enum SpecialEnum implements Named {
    FIRST("First"), SECOND("Second");

    private String name;

    SpecialEnum(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }
}

public void displayName(Named specialClass) {
    System.out.println(specialClass.getName());
}

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