mardi 25 octobre 2022

Avoid Unchecked cast warning to generic Type when using reflection

I have a piece of code which looks like this,

the field is a private static final HashMap from a source code which I need to modify.

void <T extends MyInterface> registerMyClass (Class<T> myClass) throws NoSuchFieldException, 
                                                                       IllegalAccessException, 
                                                                       ClassCastException {

    Field field = SomeClass.class.getDeclaredField(FIELD_NAME);
    field.setAccessible(true);
    Map<Class, Collection<Class<?>>> map = (Map<Class, Collection<Class<?>>>) field.get(null);
    Collection<Class<?>> classes= map.computeIfAbsent(KeyClass.class, k -> new LinkedList<>());
    
    if (!classes.contains(myClass)) {
        services.add(myClass);
    }

}

I would like to do this without getting an Unchecked warning which does not comply with the requirements for a merge request.

Is there an approach to achieve the same result without causing an unchecked cast warning?





Aucun commentaire:

Enregistrer un commentaire