2016-03-01 95 views
2

這是我目前枚舉類:如何在Java中使用單獨的枚舉類引用靜態類?

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 
} 
} 

由於把評價和(*),是否有可能引用靜態類枚舉裏面,所以我可以通過只引用更改類的內部靜態值建築類型?

例如

BuildingType.MINER.getReferencedClass.setCookiesPerSecond(4); 

感謝所有,
雅科:)

回答

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

是的,你可以引用他們的名字,然後.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 {} 
}