小编Phi*_*ham的帖子

从java反射方法调用转换返回

我正在尝试编写一个泛型方法,该方法将基于通过反射调用方法来散列对象列表.这个想法是调用者可以指定哪个方法将生成用于散列的密钥.我的问题是我想避免@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)

java generics reflection list hashmap

2
推荐指数
1
解决办法
2300
查看次数

标签 统计

generics ×1

hashmap ×1

java ×1

list ×1

reflection ×1