Skip to content
Advertisement

Get Values of variables under an Enum

I want to write into a file/print the constants of an enum, as well as the values of their variables.

For example, here is what I thought of doing:

id, field_name_1, field_name_2, ...
enum_id, field_value_1, field_value_2, ...
...

However, I am not fully sure on how to do such a thing, as I only recently began working with reflection.

This is the code that I currently have.

public static void writeEnum(String filename, Enum e, SnelPlugin plugin){
        SnelTextFile file = new SnelTextFile(plugin, new File(plugin.getDataFolder() + "/" + filename + ".txt"));
        Logger.debug("Starting an EnumWriter for " + filename + ".txt for plugin " + plugin.getPluginName());

    try {
        file.openWriter(true);

        Field[] fields = e.getClass().getFields();

        // HEADER
        String info = "";
        for(Field f: fields) {
            info += ", " + f.getName();
            Logger.debug("Detected value: " + f.getName());
        }
        info = info.replaceFirst(", ", "");
        file.addLine(info);

        // CONTENT
        for(Object current: e.getDeclaringClass().getEnumConstants()){
            Logger.debug(current.toString());

            String result = "";

            for(Field f: fields){
                result += ", " + f.get(current);
            }

            result = result.replaceFirst(", ", "");

            file.addLine(result);

            Logger.debug("Added row: " + result);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }finally {
        try {
            file.closeWriter();
        } catch (IOException e1) {
        }
    }

    Logger.log(LColor.GREEN + "Finished an EnumWriter action on " + filename + ".txt from " + plugin.getPluginName());
}

Here is the Enum (APIPerm), which I setup for a simple test:

COMMANDS_SNELAPI,
COMMANDS_SNELAPI_INFO;

private String id;

APIPerm(){
    id = getID();
}

@Override
public String getPrefix() {
    return "snelapi";
}

@Override
public String getID(){
    return getPrefix() + "." + this.toString().toLowerCase().replaceAll("_", ".");
}

However, I get an NPE in for(Object current: e.getDeclaringClass().getEnumConstants())

Thanks for your help, Sneling.

Advertisement

Answer

Thanks to @Pshemo and @MarkusFisher, I’ve come to a solution.

Note that this method DOES include other classes and methods, but they don’t affect the way this method works.

If you want to test for yourself:

  • Logger.debug can be replaced with System.out.println, LColor should be deleted
  • SnelPlugin is only needed for the Logger.debug and locating a directory.
  • SnelTextFile is just a class to make creating text files easier. Remove if you’re only printing.

Method Code:

public static <E extends Enum<E>> void writeEnum(String fileName, Class<E> c, SnelPlugin plugin){
    SnelTextFile file = new SnelTextFile(plugin, new File(plugin.getDataFolder() + "/" + fileName + ".txt"));
    Logger.debug("Starting EnumWriter for " + file.getFile().getName(), plugin);

    try {
        file.openWriter(true);
        Logger.debug("Opened FileWriter", plugin);

        Field[] classFields = c.getDeclaredFields();

        String header = "Value";

        for(Field f: classFields){
            if(!Modifier.isStatic(f.getModifiers())) {
                header += ", " + f.getName();
                Logger.debug("Discovered variable '" + f.getName() + "'", plugin);
            }
        }

        file.addLine(header);
        file.addLine("");

        for(E en: c.getEnumConstants()){
            Logger.debug("Reading Enum Constant: " + en.toString(), plugin);
            Field[] fields = en.getDeclaringClass().getDeclaredFields();

            String current = en.toString();

            for(Field f: fields){
                if(!Modifier.isStatic(f.getModifiers())){
                    f.setAccessible(true);
                    current += ", " + f.get(en);
                    Logger.debug("Value for '" +f.getName() + "' = '" +  f.get(en) + "'" , plugin);
                }
            }

            file.addLine(current);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }finally {
        try {
            file.closeWriter();
            Logger.debug("Closer FileWriter");
        } catch (IOException ex) {
        }
    }

    Logger.log(LColor.GREEN + "Finished EnumWriter for " + file.getFile().getName() + ". It can be found at " + file.getFile().getPath(), plugin);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement