Java: instantiating an enum using reflection

前端 未结 5 1472
甜味超标
甜味超标 2020-12-08 09:07

Suppose you have a text file like:

my_setting = ON
some_method = METHOD_A
verbosity = DEBUG
...

That you wish to to update a corresponding

5条回答
  •  眼角桃花
    2020-12-08 10:05

    The accepted answer results in warnings because it uses the raw type Enum instead of Enum>.

    To get around this you need to use a generic method like this:

    @SuppressWarnings("unchecked")
    private > T createEnumInstance(String name, Type type) {
      return Enum.valueOf((Class) type, name);
    }
    

    Call it like this:

    Enum enum = createEnumInstance(name, field.getType());
    field.set(this, enum);
    

提交回复
热议问题