java - 从不同对象获取值的通用方法,无需通用超类型
问题描述
我正在使用一个开放的 API(所以不能更改他们这边的代码),它提供了一个枚举值类型的数组。
User.IDType.values();
问题在于上述数组中的每种类型。我必须调用一个 value() 函数来为提供的类型返回一个字符串值数组。
public static String[] enumValues(IDType[] types) {
String[] values = new String[types.length];
for ( int i=0; i < types.length; i++ ) {
values[i] = types[i].value();
}
return values;
}
为了避免为每种类型编写此函数,我想编写如下所示的泛型方法,但问题是:如何调用泛型类型的函数值?
static <T> String[] enumValues(T[] types)
{
String[] values = new String[types.length];
for (int i=0; i<types.length; i++) {
values[i] = types[i].value;
}
return values;
}
注意:任何类型都没有超类 ex: Type,我可以使用它。
解决方案
由于您有以下限制:
任何类型都没有超类 ex: Type,我可以使用它。
剩下的解决方案是使用反射 API。但是,这样的解决方案不是类型安全的,运行时错误,而不是在 Enum 中更改方法时会抛出编译时错误。value
以下是使用反射 API 的示例。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class GenericEnumTest {
static <T> String[] enumValues(T[] types) {
String[] values = new String[types.length];
for (int i = 0; i < types.length; i++) {
Method valueMethod;
try {
valueMethod = types[i].getClass().getMethod("value");
values[i] = (String) valueMethod.invoke(types[i]);
} catch (NoSuchMethodException | SecurityException | IllegalArgumentException | IllegalAccessException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
return values;
}
public static void main(String[] args) {
String[] result = enumValues(new IDType[] { IDType.TEST1, IDType.TEST2 });
System.out.println(Arrays.toString(result));
}
public static enum IDType {
TEST1("test1"), TEST2("test2");
private IDType(String value) {
this.value = value;
}
private String value;
public String value() {
return value;
}
}
}
推荐阅读
- eclipse - 有没有办法将智能插入添加到自定义 Eclipse 编辑器?
- reactjs - React Hooks - 改变孩子内部的状态不会反映在父母身上
- python - 使用堆栈溢出数据文件的熊猫数据帧
- html - 使用 flex-direction 列反向定位粘性
- amazon-mws - 销售伙伴 API 供稿 API
- multithreading - 为什么用Receiver声明receiver
? - dvc - 数据版本控制 (dvc) 无法推送到远程存储,因为查询缓存
- c++ - 为什么 shared_ptr 在函数中返回时没有隐式转换为布尔值?
- python - 如何在多重赋值语句中添加换行符?
- reactjs - 为不同的路由使用不同的模板反应路由器 v. 5