Phi*_*ham 2 java generics reflection list hashmap
我正在尝试编写一个泛型方法,该方法将基于通过反射调用方法来散列对象列表.这个想法是调用者可以指定哪个方法将生成用于散列的密钥.我的问题是我想避免@SuppressWarnings("unchecked")注释.所以本质上我想找到一种方法来获取method.invoke以返回T2类型的对象而不是Object.在此先感谢您的帮助.
public static <T1, T2> HashMap<T2, T1> hashFromList(
List<T1> items_to_be_hashed,
String method_name_to_use_to_generate_key) {
HashMap<T2, T1> new_hashmap = new HashMap<>(items_to_be_hashed.size() + 5, 1);
for (T1 object_to_be_hashed : items_to_be_hashed) {
try {
//Call the declared method for the key
Method method = object_to_be_hashed.getClass().getDeclaredMethod(method_name_to_use_to_generate_key);
@SuppressWarnings("unchecked")
T2 key = (T2) method.invoke(object_to_be_hashed);
new_hashmap.put(key, object_to_be_hashed);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException exception) {
exception.printStackTrace();
}
}
return new_hashmap;
}
Run Code Online (Sandbox Code Playgroud)
避免抑制警告并具有真正的强制转换(可以捕获问题)的唯一方法是T2
在执行时知道,您可以通过额外的参数来执行:
... hashFromList(List<T1> itemsToHash,
String generationMethod,
Class<T2> clazzT2)
Run Code Online (Sandbox Code Playgroud)
然后你可以使用Class.cast
:
T2 key = clazzT2.cast(method.invoke(objectToHash));
Run Code Online (Sandbox Code Playgroud)