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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:00:24  来源:igfitidea点击:

Raw use of parameterized class

javagenerics

提问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 getStaticFieldValuesto 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)