【问题标题】:Convert via reflection retrieved object to string (how to iterate over multiple class types?)通过反射检索到的对象转换为字符串(如何迭代多个类类型?)
【发布时间】:2015-08-28 15:20:21
【问题描述】:

我有一个 getterMethod,它返回我使用检索的类型:

getterMethod.getReturnType()

我需要将此返回值转换为字符串。根据返回值的类型,我要么只需要在对象上使用.toString() 方法,有时我需要做更多的工作,比如对日期使用字符串格式等。

我情不自禁地走上了这条路:

Integer i = 1;
if(i.getClass().isInstance(getterMethod.getReturnType())){
    // integer to string
}

但是我有很多可能的类型,什么是解决这个问题的好方法?

是否可以在类类型上使用 switch case 块?

【问题讨论】:

  • 您可以写getterMethod.getReturnType() == Integer.class,要转换为字符串,您可以调用toString(),这适用于多种类型。
  • 当我得到一个日期对象时,我需要一个非常特殊的格式。简单地使用 .tostring 是不行的,这就是我开始这个问题的原因;)
  • 一个想法,我们可以做一些类似的事情:StringBuilder sb = new StringBuilder(); sb.append(anything); String result = sb.toString();。不过,您必须针对特定的日期格式对其进行调整。

标签: java class parsing reflection instanceof


【解决方案1】:

您只需执行以下操作:

String objectCLassName = obj.class.getName();

这是一个通用对象的类名字符串。

如果您的方法返回一个字符串,只需将其与这个进行比较。

例如

String returnType = getterMethod.getReturnType();
if (i.class.getName().equals(returnType)) {
    // Your code here
}

【讨论】:

    【解决方案2】:

    由于分层特性和继承性,一些冗长的内容仍然存在。

    面向对象将是一张地图。

    Class<?> clazz = getterMethod.getReturnType();
    

    请注意,这里的继承是残酷的:子类可能会返回 超类中返回类型的派生类;并拥有两者 相同签名的 getter 方法。

    您可能需要针对从 getter 接收到的值处理 Class.isPrimitive(Integer.classint.class)。

    还有Class.isArrayType之类的。

    但是类型转换器的映射是可行的:

    Map<Class<?>, Function<Object, String>> map;
    
    Function<Object, String> converter;
    do {
         converter = map.get(clazz);
         clazz = clazz.getSuperclass();
    } while (converter == null && clazz != null;
    
    String asText = converter == null
        ? String.valueOf(value)
        : converter.apply(value);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2012-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多