本文介绍了原始使用参数化类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个辅助方法,用于通过反射获取指定类型的静态字段的值.该代码运行正常,但是我在网上收到原始使用参数化类"警告:
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);
问题在于类型参数T可以是泛型.有没有办法重写方法 getStaticFieldValues
来解决此问题?
The issue is that type parameter T can be generic type. Is there way to rewrite method getStaticFieldValues
to work around this issue?
代码清单:
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");
}
}
推荐答案
方法getStaticFieldValues()的定义更改:
in the definition of method getStaticFieldValues() change:
getStaticFieldValues(Class<?> fieldSource, Class<T> fieldType)
到
getStaticFieldValues(Class<?> fieldSource, Class<?> fieldType)
这篇关于原始使用参数化类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!