Raw use of parameterized class

JavaGenerics

Java Problem Overview


I wrote a helper method for getting values of static fields of specified type via reflection. The code is working fine, but I am getting "raw use of parameterized class" warning on line:

final List<Collection> fields = getStaticFieldValues(Container.class, Collection.class);

The issue is that type parameter T can be generic type. Is there way to rewrite method getStaticFieldValues to work around this issue?

Code listing:

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;

import java.lang.reflect.*;
import java.util.*;

import org.junit.Test;

public class GenericsTest {

    @Test
    public void test() {
        // Warning "raw use of parameterized class 'Collection'"
        final List<Collection> fields = getStaticFieldValues(Container.class, Collection.class);
        assertEquals(asList("A", "B", "C"), fields.get(0));
    }

    private static <T> List<T> getStaticFieldValues(Class<?> fieldSource, Class<T> fieldType) {
        List<T> values = new ArrayList<>();
        Field[] declaredFields = fieldSource.getDeclaredFields();
        for (Field field : declaredFields) {
            if (Modifier.isStatic(field.getModifiers()) && fieldType.isAssignableFrom(field.getType())) {
                try {
                    final T fieldValue = (T) field.get(null);
                    values.add(fieldValue);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Error getting static field values");
                }
            }
        }
        return values;
    }

    public static class Container<T> {
        public static Collection<String> elements = asList("A", "B", "C");
    }
}

Java Solutions


Solution 1 - Java

in the definition of method getStaticFieldValues() change:

getStaticFieldValues(Class<?> fieldSource, Class<T> fieldType)
                                                ^^^

to

getStaticFieldValues(Class<?> fieldSource, Class<?> fieldType)
                                                ^^^

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondsavickasView Question on Stackoverflow
Solution 1 - JavaEduSanConView Answer on Stackoverflow