简体   繁体   English

Java泛型:如何处理原始类型成员变量并避免出现警告?

[英]Java Generics: how handle raw type member variable and avoid warnings?

I have a class that has a raw type member variable called Argument<T> . 我有一个类,它具有一个称为Argument<T>的原始类型成员变量。 The class is meant to simply wrap around this type, and assign all values via the constructor in a generic way, because the type of Argument and of the parameters passed to the constructor is not known at compile time. 类是为了简单的解决此类型的包,并通过构造一个通用的方式分配所有值,因为类型Argument ,并传递给构造函数的参数是不是在编译时已知。

public class ArgumentWrapper {

    private Argument argument;

    public ArgumentImplementation(Class<?> type, String name, 
            Object defaultValue, Set<?> allowedValues, 
            Comparable<?> lowerBound, Comparable<?> upperBound) {
        argument = new Argument<>(type);
        argument.setName(name);
        argument.setDefaultValue(defaultValue);
        argument.setAllowedValues(allowedValues);
        argument.setLowerBound(lowerBound);
        argument.setUpperBound(upperBound);
    }

    // some getters...

}

Now in my code I get a lot of warnings saying 现在在我的代码中,我收到很多警告说

Argument is a raw type. References to generic type Argument<T> should be 
parameterized

at the member and 在成员和

Type safety: The method setDefaultValue(Object) belongs to the raw type Argument.
References to generic type Argument<T> should be parameterized

where the constructor parameters are assigned to it. 分配了构造函数参数的位置。

I know I cannot change the member to private Argument<?> argument; 我知道我无法将成员更改为private Argument<?> argument; because then I get errors when the generic parameters are assigned to it in the constructor. 因为当在构造函数中将通用参数分配给它时,我得到了错误。

What is your recommendation to handle this? 您对此有何建议? How do I avoid these warnings without introducing errors? 如何避免这些警告而又不引入错误? How can I handle the generic type member variable different / better? 如何处理不同/更好的通用类型成员变量?

With help of a comment and some trying back and forth I got the answer myself. 在评论的帮助和一些来回的尝试下,我自己得到了答案。

The ArgumentWrapper class should be generic, and the generic type T should be used everywhere. ArgumentWrapper类应该是通用的,并且通用类型T应该在所有地方使用。

public class ArgumentWrapper<T> {

    private Argument<T> argument;

    public ArgumentImplementation(Class<T> type, String name, 
            T defaultValue, Set<T> allowedValues, 
            Comparable<T> lowerBound, Comparable<T> upperBound) {
        argument = new Argument<T>(type);
        argument.setName(name);
        argument.setDefaultValue(defaultValue);
        argument.setAllowedValues(allowedValues);
        argument.setLowerBound(lowerBound);
        argument.setUpperBound(upperBound);
    }

    // some getters...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM