samedi 13 février 2021

Java: Adding an enum value on runtime

I have the following class.

package net.runelite.client.plugins;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter(AccessLevel.PUBLIC)
@AllArgsConstructor
public enum PluginType
{
    PVM("PvM"),
    PVP("PvP"),
    SKILLING("Skilling"),
    UTILITY("Utilities"),
    MISCELLANEOUS("Miscellaneous"),
    SYSTEM("System"),
    MINIGAME("Minigame"),
    GAMEMODE("Gamemode"),
    UNCATEGORIZED("Uncategorized");

    private final String name;

    @Override
    public String toString()
    {
        return getName();
    }
}

I need to add in an enum in the class above.

And in my use case i cannot modify the class itself so i need a way to inject/add one in there on runetime.

I was thinking of a method below, but did not find a working way to implent this.

try {
    Method valueOf = field.getType().getMethod("valueOf", String.class);
    Object value = valueOf.invoke(null, param);
    field.set(test, value);
} catch ( ReflectiveOperationException e) {

}




Aucun commentaire:

Enregistrer un commentaire