[Util] easy configuration!

Discussion in 'Resources' started by 2016mfransen, Jun 27, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    2016mfransen

    Hi recently I have create a util that allows you to easily load and save your config to a class

    How it works:
    The util will read all the fields in a class provided and fill them with config values (defaults to value if path isn't found in config)

    Example:
    Code:java
    1. public class MyPlugin extends JavaPlugin
    2. {
    3. public void onEnable()
    4. {
    5. ConfigUtil.saveDefaultConfig(new File(getDataFolder(),"config.yml"));
    6. ConfigUtil.load(MyConfig.class, getConfig())
    7. getLogger().info(MyConfig.testBoolean); //prints out config value for testBoolean or defaults to true
    8. }
    9. public void onDisable()
    10. {
    11. ConfigUtil.save(MyConfig.class, getConfig())
    12. saveConfig()
    13. }
    14. }
    15. public class MyConfig
    16. {
    17. //must have default value
    18. //must be static
    19. public static boolean testBoolean = true;
    20. public static int testInt = 0;
    21. public static MemorySection = new YamlConfiguration()
    22. }

    Util Class:
    Code:java
    1. //can also be found at [url]http://pastebin.com/2m4B7La0[/url]
    2. public class ConfigUtil {
    3. public static void load(Class<?> configClass, ConfigurationSection config)
    4. {
    5. for(Field f : configClass.getDeclaredFields())
    6. {
    7. try {
    8. f.set(null, config.get(f.getName(),f.get(null)));
    9. continue;
    10. } catch (IllegalAccessException e) {
    11. continue;
    12. }
    13. }
    14. }
    15. public static void save(Class<?> configClass, ConfigurationSection config)
    16. {
    17. for(Field f : configClass.getDeclaredFields())
    18. {
    19. try {
    20. config.set(f.getName(), f.get(null));
    21. continue;
    22. } catch (IllegalAccessException e) {
    23. continue;
    24. }
    25. }
    26. }
    27. public static void saveDefaultConfig(Class<?> configClass, File file)
    28. {
    29. if(file.exists())
    30. return;
    31. FileConfiguration config = new YamlConfiguration();
    32. load(configClass,config);
    33. try {
    34. config.save(file);
    35. } catch (IOException e) {
    36. e.printStackTrace();
    37. }
    38. }
    39. }
     
  2. Offline

    Phasesaber

    So, you made a util that adds backups for config values?
     
  3. Offline

    AoH_Ruthless

    2016mfransen

    Uh, can you at least explain how to use it? I just see a bunch of complicated code and have no idea where to start ..
     
Thread Status:
Not open for further replies.

Share This Page