Casting the return from a java reflection method invocation
generics, hashmap, java, list, reflection
Solution
The only way to avoid suppressing warnings and have a true cast (which would catch problems) is to know `T2` at execution time, which you can do via an extra parameter:
... hashFromList(List<T1> itemsToHash,
String generationMethod,
Class<T2> clazzT2)
You can then use `Class.cast`:
T2 key = clazzT2.cast(method.invoke(objectToHash));
Problem
I am trying to write a generic method that will hash a list of objects based on calling a method through reflection. The idea is that the caller can specify which method will generate the keys for hashing. My problem is that I want to avoid the @SuppressWarnings("unchecked") annotation. So in essence I want to find a way to get method.invoke to return an object of Type T2 rather than Object. Thanks in advance for any help. ``` 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; } ```