使用 REST api,我有以下设置:
public enum Ready {
YES,
NO;
}
public class Top {
public Ready readyField;
}
其中一些:
public class Bottom extends Top {
... some fields
}
现在,我正在对扩展 Top 类的类进行过滤。因此,我使用反射来尝试获取字段值,如果过滤器失败,则不会返回实例。
这样的过滤器可以位于“readyField”上。假设我的网址如下所示:“http.../?isReady=no”。
我的代码如下所示:
Field field = Bottom.class.getField("readyField");
Class<?> type = field.getType();
if (type.isEnum()) {
Object object = field.get(Bottom.class);
if (!object.toString().equalsIgnoreCase(value)) {
resultList.remove(instance);
continue;
}
}
值字段是 URL 中的“no”字符串。
这会抛出一个异常:
java.lang.IllegalArgumentException: Can not set Ready field Top.readyField to java.lang.Class
我很困惑。我在 Google 上能找到的所有内容都与从枚举类本身获取枚举值有关。与尝试使用该枚举来比较类中分配的枚举字段的字符串值无关。
我已经获得了我需要的对象实例。我需要的是获取类中枚举的值并将其与给定的字符串进行比较。
编辑:
解决方案似乎不是使用 Bottom.class,而是使用 get() 函数的所述类的实际实例。
这就是已接受的答案所说的内容,但措辞对我来说有点奇怪。
最佳答案
Field#get(Object)
的参数需要是字段出现的实例,而不是此类实例的 Class 对象。
Returns the value of the field represented by this
Field
, on the specified object.
所以你需要类似的东西
Bottom bottom = ...;
...
Object object = field.get(bottom);
同样,Field#set(Object, Object)
期望第一个参数是要设置字段值的实例。
Sets the field represented by this
Field
object on the specified object argument to the specified new value.
关于java - 无法从类中获取枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26282522/