Using Spring IoC to set up enum values

后端 未结 13 2020
名媛妹妹
名媛妹妹 2020-11-30 06:06

Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded i

13条回答
  •  一个人的身影
    2020-11-30 06:09

    All right, this is a bit complex but you may find a way to integrate it. Enums are not meant to change at runtime, so this is a reflection hack. Sorry I don't have the Spring implementation part, but you could just build a bean to take in the enum class or object, and another field that would be the new value or values.

    Constructor con = MyEnum.class.getDeclaredConstructors()[0];
    Method[] methods = con.getClass().getDeclaredMethods();
    for (Method m : methods) {
      if (m.getName().equals("acquireConstructorAccessor")) {
        m.setAccessible(true);
        m.invoke(con, new Object[0]);
      }
    }
    Field[] fields = con.getClass().getDeclaredFields();
    Object ca = null;
    for (Field f : fields) {
      if (f.getName().equals("constructorAccessor")) {
        f.setAccessible(true);
        ca = f.get(con);
      }
    }
    Method m = ca.getClass().getMethod(
      "newInstance", new Class[] { Object[].class });
    m.setAccessible(true);
    MyEnum v = (MyEnum) m.invoke(ca, new Object[] { 
      new Object[] { "MY_NEW_ENUM_VALUE", Integer.MAX_VALUE } });
      System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());
    

    This is taken from this site.

提交回复
热议问题