简体   繁体   English

如何使用Java-Reflection设置scala.Enumeration类型的值

[英]How to use Java-Reflection to set the value of type scala.Enumeration

I have a complicated reflection-based Java-Application which I now translated partly into scala. 我有一个复杂的基于反射的Java应用程序,现在将其部分翻译为scala。 Howerver, the reflection-based part is still in Java ... 但是,基于反射的部分仍在Java中...

Now I have a scala enumeration type, for instance: 现在,我有一个scala枚举类型,例如:

object DayType extends Enumeration {
  type DayType = Value

  val Monday = Value("Monday")
  val Tuesday = Value("Tuesday")
  ...
}

Now I use Java Reflection in a following way: 现在,我通过以下方式使用Java Reflection:

public static void setFieldValue(Object o, String fieldName, String value) {

  Field field;
  try {
    field = o.getClass().getField(fieldName);
  } catch (NoSuchFieldException e) {
    // in Scala EVERY field is private.
    field = o.getClass().getDeclaredField(fieldName);
    field.setAccessible(true);
  }

  Class type = field.getType();
  if (type == Float.TYPE) {
    field.setFloat(o, Float.parseFloat(value));
  } 
  if (type == Integer.TYPE) {
    field.setInt(o, Integer.parseInt(value));
  }

  ...

  if (type.getName().equals("scala.Enumeration$Value")) {
    System.out.println("fieldname: " + field.getName());
    System.out.println("fieldtype: " + field.getType());
    try {
      field.set(o, ???);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

  ...

At least the type recognition works correctly, however, two questions remain: 1. Is there a way to recognize the type without going via the name? 至少类型识别可以正常工作,但是,还有两个问题:1.是否有一种无需通过名称即可识别类型的方法? if (type == Enumeration.class) does not work, if (type == Enumeration) also not (the second solution does not even compile) 2. How to set the value? if(type == Enumeration.class)不起作用,if(type == Enumeration)也不起作用(第二个解决方案甚至无法编译)2.如何设置值? How to replace "???" 如何替换“ ???” Simply doing field.set(o, value) leads to a "Can not set scala.Enumeration$Value field diva.module.AdaptationFloodingNew.adaptMode to java.lang.String" exception (which is reasonable). 简单地执行field.set(o,value)会导致“无法将scala.Enumeration $ Value字段diva.module.AdaptationFloodingNew.adaptMode设置为java.lang.String”(这是合理的)。

What is missing from the code is a way to convert the value from a string to a DayType. 代码中缺少的是一种将值从字符串转换为DayType的方法。 Kind of like the way the Integer is handled... Integer.parseInt(value). 有点像处理整数的方式... Integer.parseInt(value)。 Try using the Value construct that is used in the DayType Enumeration. 尝试使用DayType枚举中使用的Value构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM