Search code examples
javareflectionenumsjavassist

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("br.com.alinesolutions.anotaai.*").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()) {
                System.out.println(field);
                //CtMethod m = CtNewMethod.make("public String getType() { return this.toString(); }", ctClass);
                //ctClass.addMethod(m);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

how to create a method in enum field?


Solution

  • 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.