如何在Java中引用带有单独枚举类的静态类?

时间:2016-03-01 12:08:37

标签: java class enums static

这是我目前的枚举类:

public enum BuildingType {
MINER("Miner", "A basic slave." (*, Miner (separate class)*)), FARM("Farm", "Old Macdonald's Crib."), BAKERY("Bakery", "Best Cookies in Town!"), FACTORY("Factory", "Highest Quality Memes in town!"), QUARRY("Quarry", "Let's get drilling!");

private String name;
private String description;
//private Class clazz;

BuildingType(String name, String description (* Possible to put Class clazz reference here? *)) {
    this.name = name;
    this.description = description;
    //this.clazz = clazz
}

public String getName() {
    return name;
}

public String getDescription() {
    return description;
}

public Class getReferencedClass() {
    //Return referenced "clazz" above
}
}

如注释和(* *)中所述,是否可以在枚举中引用静态类,以便我可以通过引用构建类型来更改该类中的静态值?

e.g。

BuildingType.MINER.getReferencedClass.setCookiesPerSecond(4);

谢谢大家,
哈科:)

2 个答案:

答案 0 :(得分:2)

你可以使用反射来做到这一点,但是为这个类实现一个实例会更好,它实现了所有其他实现实现的接口,即使该接口只有一个实例,例如。

enum StaticData implement IData {
    INSTANCE; // only one instance

    /* put your non static fields here */

    /* put your methods for IData here */
}

public enum BuildingType {
    MINER("Miner", "A basic slave.", StaticData.INSTANCE), FARM("Farm", "Old Macdonald's Crib."), BAKERY("Bakery", "Best Cookies in Town!"), FACTORY("Factory", "Highest Quality Memes in town!"), QUARRY("Quarry", "Let's get drilling!");

// later
BuildingType.MINER.getIData().setCookiesPerSecond(4);

答案 1 :(得分:1)

是的,您可以按名称引用类,然后是.class惯用语。 在你的例子中显示:

public enum BuildingType {
    MINER("Miner", "A basic slave.", Miner.class), FARM("Farm", "Old Macdonald's Crib.", Farm.class),
    BAKERY("Bakery", "Best Cookies in Town!", Bakery.class),
    FACTORY("Factory", "Highest Quality Memes in town!", Factory.class),
    QUARRY("Quarry", "Let's get drilling!", Quarry.class);

    private String name;
    private String description;
    private Class<?> clazz;

    BuildingType(String name, String description, Class<?> clazz) {
        this.name = name;
        this.description = description;
        this.clazz = clazz;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public Class<?> getReferencedClass() {
        return clazz;
    }

    public static class Miner {}

    public static class Farm {}

    public static class Bakery {}

    public static class Factory {}

    public static class Quarry {}
}