Does anyone know how to get the value of an enum object from a custom yml file? Code: public static QuestTyp getQuestQuestTyp(String questname) { String questTyp = FileHandler.quests.getString(questname+".QuestTyp"); QuestTyp quest = QuestTyp.valueOf(questTyp); return quest; } I want to get the typ of the quest with the methode. The methode should return the value of an enum object (QuestTyp). How can I read a simple input in the yml file. Thats my yml file: Code: quest1: Name: 'Killer' Description: 'We was conquered by Creepers. Kill them!' QuestTyp: 'kill' //Thats an enum value. ObjectTyp: 'Creeper' // Thats an enum value too reqAmount: 10 MoneyReward: 40 quest2: Does anyone know a good way to "read" and return it?? My code doesnt work. There is a Nullpointer error. Hope you understand my problem. Thanks.
Unfortunately YamlConfiguration doesn't have built in support for Enum values. You can use something like this; Code:JAVA public Enum getEnum(Class clazz, String string) throws Exception { if(!clazz.isEnum()) throw new Exception("Class "+clazz.getName()+" is not an enum."); for(Object constant : clazz.getEnumConstants()) { if(((Enum) constant).toString().equals(string)) { return (Enum) constant; } } throw new Exception("String "+string+" not a valid enum constant for "+clazz.getName());} That's the method I use in my SuperEasyConfig. To use it with your example it would be; Code:JAVA public static QuestTyp getQuestQuestTyp(String questname) { String questTyp = FileHandler.quests.getString(questname+".QuestTyp"); QuestTyp quest = null; try { quest = getEnum(QuestTyp.class, questTyp); } catch(Exception ex) { ex.printStackTrace(); return null; } return quest;}
Thank you very much. I'll test it. Im very worry about it but it doesnt work. There is still a Nullpointer error. I casted quest = getEnum(QuestTyp.class, questTyp); to quest = (QuestTyp) getEnum(QuestTyp.class, questTyp); Please help me! EDIT by Moderator: merged posts, please use the edit button instead of double posting.
Sorry, forgot about the reflection trickiness I used around this. Try; Code:JAVA public static QuestTyp getQuestQuestTyp(String questname) { String questTyp = FileHandler.quests.getString(questname+".QuestTyp"); QuestTyp quest = null; try { quest = QuestTyp.values()[getEnum(QuestTyp.class, questTyp).ordinal()]; } catch(Exception ex) { ex.printStackTrace(); return null; } return quest;}
Sorry. It worked with my original code. I used a wrong variable to call the methode. I used not the username but a not inialized variable. Very nooby mistake. xDDD But thanks for your source code examples.