【发布时间】: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