Search code examples
javareflectioncasting

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?

EDIT:

I should have formulated the question more clearly, what I need to do is to modify the value in the private static final hashmap without performing an unchecked cast, the field is from a source file so I cannot modify the methods for handling it, so I resorted to reflection.

Basically now it works but I can't merge the code because it's too ugly :( and doesn't pass the automatic code-check, so I need some other approach.


Solution

  • You will not be able to get rid of the warning on the cast itself. The only thing you can do is suppress the warning using the @SuppressWarnings annotation:

    ...
    Field field = SomeClass.class.getDeclaredField(FIELD_NAME);
    field.setAccessible(true);
    
    @SuppressWarnings("unchecked")
    Map<Class, Collection<Class<?>>> map = (Map<Class, Collection<Class<?>>>) field.get(null);
    
    Collection<Class<?>> classes= map.computeIfAbsent(KeyClass.class, k -> new LinkedList<>());
    ...