参数化类的原始使用
我编写了一个帮助器方法,用于通过反射获取指定类型的静态字段的值。代码工作正常,但我在行上收到“原始使用参数化类”警告:
final List<Collection> fields = getStaticFieldValues(Container.class, Collection.class);
问题是类型参数 T 可以是泛型类型。有没有办法重写方法来解决这个问题?getStaticFieldValues
代码清单:
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");
}
}