samedi 3 septembre 2016

Get Values of variables under an Enum

I want to, basically, make some very cheap way to see the values of all the variables in an Enum class, as well as read the value for each Field on each enum inside this class.

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, which I setup for a simple test: http://ift.tt/2cyqvN8

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

FYI, Before getting this error, my txt file used to be empty.

Thanks for your help, Sneling.





Aucun commentaire:

Enregistrer un commentaire