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. Howerver, the reflection-based part is still in Java ... Now I have a scala enumeration type, for instance: object DayType extends Enumeration { type DayType = Value val Monday = Value("Monday") val Tuesday = Value("Tuesday") ... } Now I use Java Reflection in a following way: 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? 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? 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).
To my knowledge I don't think there is. Reflection is great just make sure you comment it well. Uses of Reflection don't pop up when looking for calls to methods using the find feature.

以上就是How to use Java-Reflection to set the value of type scala.Enumeration的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏