java Eclipse 警告 - 类是原始类型。对泛型类型 Class<T> 的引用应该被参数化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11885022/
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-10-31 06:47:05  来源:igfitidea点击:

Eclipse warning - Class is a raw type. References to generic type Class<T> should be parameterized

javagenerics

提问by CodeBlue

import java.util.ArrayList;

public class ListOfClasses
{

    private ArrayList<Class> classes;

    public ArrayList<Class> getClasses() 
    {
        return classes;
    }

    public void setClasses(ArrayList<Class> classes) 
    {
        this.classes = classes;
    }
}

For this, I get the following warning in eclipse -

为此,我在 Eclipse 中收到以下警告 -

Class is a raw type. References to generic type Class should be parameterized

类是原始类型。对泛型类型 Class 的引用应该被参数化

This was asked in an earlier question, but the answer was specific to the Spring Framework. But I am getting this warning even without having anything to do with Spring. So what is the problem?

这是在较早的问题中提出的,但答案是特定于 Spring 框架的。但是即使与 Spring 无关,我也会收到此警告。那么问题出在哪里呢?

回答by Peter Lawrey

I suspect its complaining that Class is a raw type. You can try

我怀疑它抱怨 Class 是原始类型。你可以试试

private List<Class<?>> classes;

or suppress this particular warning.

或取消此特定警告。

I would ignore the warning in this case. I would also consider using a defensive copy.

在这种情况下,我会忽略警告。我也会考虑使用防御性副本。

private final List<Class> classes = new ArrayList<>();

public List<Class> getClasses() {
    return classes;
}

public void setClasses(List<Class> classes) {
    this.classes.clear();
    this.classes.addAll(classes);
}

回答by Edwin Dalorzo

Try

尝试

public class ListOfClasses
{

    private ArrayList<Class<?>> classes;

    public ArrayList<Class<?>> getClasses() 
    {
        return classes;
    }

    public void setClasses(ArrayList<Class<?>> classes) 
    {
        this.classes = classes;
    }
}

Class is a parameterized type as well, and if you do not declare a type argument, then you get a warning for using raw types where parameterized types are expected.

Class 也是参数化类型,如果您没有声明类型参数,那么您会收到警告,因为在需要参数化类型的地方使用原始类型。

回答by Stimpson Cat

The problem is that you can not say anything about the type of returned class. This warning is not very useful. Since you dont knwow which type of class it is, you cannot add type arguments to it. If you do it like this:

问题是你不能说明返回的类的类型。这个警告不是很有用。由于您不知道它是哪种类型的类,因此您无法向其添加类型参数。如果你这样做:

public  Class<? extends Object> getClasses {}

You don't make it better, since everything extends Object in Java, except primitives. I ignore this hints, or turn them of.

你不会让它变得更好,因为除了原语之外,所有东西都扩展了 Java 中的 Object。我无视这个提示,或者把它们关掉。