通过反射将检索到的对象转换为字符串(如何遍历多个 class 类型?)
Convert via reflection retrieved object to string (how to iterate over multiple class types?)
我有一个 getterMethod,return 是我使用以下方法检索的类型:
getterMethod.getReturnType()
我需要将此 return 值转换为字符串。根据 returned 值的类型,我要么只需要在对象上使用 .toString()
方法,有时我需要做更多的工作,比如对日期使用字符串格式等。
我忍不住走了这条路:
Integer i = 1;
if(i.getClass().isInstance(getterMethod.getReturnType())){
// integer to string
}
但是我有很多可能的类型,什么是解决这个问题的快速好方法?
是否可以在 class 类型上使用 switch case 块?
您只需执行以下操作:
String objectCLassName = obj.class.getName();
这是通用对象 class 名称的字符串。
如果您的方法 returns 一个字符串,只需将它与这个字符串进行比较。
例如
String returnType = getterMethod.getReturnType();
if (i.class.getName().equals(returnType)) {
// Your code here
}
由于层次特征和继承性,一些冗长的内容仍然存在。
面向对象就是地图。
Class<?> clazz = getterMethod.getReturnType();
Note that already here inheritance is cruel: a child class may return
a derived class of the return type in the super class; and have both
getter methods for the same signature.
关于从 getter.
接收到的值,您可能需要处理 Class.isPrimitive(Integer.class
和 int.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);
我有一个 getterMethod,return 是我使用以下方法检索的类型:
getterMethod.getReturnType()
我需要将此 return 值转换为字符串。根据 returned 值的类型,我要么只需要在对象上使用 .toString()
方法,有时我需要做更多的工作,比如对日期使用字符串格式等。
我忍不住走了这条路:
Integer i = 1;
if(i.getClass().isInstance(getterMethod.getReturnType())){
// integer to string
}
但是我有很多可能的类型,什么是解决这个问题的快速好方法?
是否可以在 class 类型上使用 switch case 块?
您只需执行以下操作:
String objectCLassName = obj.class.getName();
这是通用对象 class 名称的字符串。
如果您的方法 returns 一个字符串,只需将它与这个字符串进行比较。
例如
String returnType = getterMethod.getReturnType();
if (i.class.getName().equals(returnType)) {
// Your code here
}
由于层次特征和继承性,一些冗长的内容仍然存在。
面向对象就是地图。
Class<?> clazz = getterMethod.getReturnType();
Note that already here inheritance is cruel: a child class may return a derived class of the return type in the super class; and have both getter methods for the same signature.
关于从 getter.
接收到的值,您可能需要处理 Class.isPrimitive(Integer.class
和 int.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);