Java 参数化类的原始使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24672749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Raw use of parameterized class
提问by dsavickas
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?
问题是类型参数 T 可以是泛型类型。有没有办法重写方法getStaticFieldValues
来解决这个问题?
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");
}
}
采纳答案by EduSanCon
in the definition of method getStaticFieldValues() change:
在方法 getStaticFieldValues() 的定义中更改:
getStaticFieldValues(Class<?> fieldSource, Class<T> fieldType)
to
到
getStaticFieldValues(Class<?> fieldSource, Class<?> fieldType)