Let's say I've got an enum like the following
public enum BindingType {
BINDING_OPEN("M1+O", "Open", true),
BINDING_SAVE("M1+S", "Save", true),
...
private BindingType(
final String sequence,
final String keyLabel,
final boolean reserved) {
this.sequence = sequence;
this.keyLabel = keyLabel;
this.reserved = reserved;
}
}
At JVM startup I'd like to add an additional value, for example
BINDING_CUSTOM("M1+U", "Custom", true)
Can this be done using Byte Buddy's AgentBuilder
?
An enum is nothing but a public static final
field of the enumeration type. You can certainly declare such a field for the enumeration type and instrument the static initializer via builder.executable(isTypeInitializer())
to set the field to a value by calling the class's constructor.
Additionally, you would probably need to instrument the class's values
method to return the additional constant with the other values and the valueOf
method to resolve the additional constant.
Enumerations are merely synthetic sugar for this combination of methods and a field. Byte Buddy offers convenience for creating new enumerations but if altering existing enumerations, you need to take some manual steps.