Gleidosn Gleidosn - 5 months ago 57
Java Question

how to create method in enum field with javassist

I'm trying to insert a method dynamically in an enum.

private void loadEnums(ServletContextEvent sce) {
List<Class<?>> classes = CPScanner.scanClasses(new ClassFilter().packageName("*").annotation(EnumSerialize.class));
CtClass ctClass = null;
EnumMemberValue enumMemberValue;
try {
for (Class<?> clazz : classes) {
if (!Enum.class.isAssignableFrom(clazz)) {
throw new RuntimeException("class " + clazz + " is not an instance of Enum");
ClassPool.getDefault().insertClassPath(new ClassClassPath(clazz));
ctClass = ClassPool.getDefault().get(clazz.getName());
for (CtField field : ctClass.getFields()) {
//CtMethod m = CtNewMethod.make("public String getType() { return this.toString(); }", ctClass);
} catch (Exception e) {

how to create a method in enum field?


I assume that you try to create a method within an enumeration, i.e.

enum Foo {
  BAR {
    void qux() { }

The Java compiler creates such a method by creating a specific class that subclasses Foo and adds the method to this class. You would need to remove the final modifier from Foo, create such a subclass and replace the static initializer that creates the enum field for this.