@SuppressWarnings for final type parameter

吃可爱长大的小学妹 提交于 2019-12-01 23:31:07

问题


Hey guys. In a place I have a method with a generic "VT extends String". Obviously this generates a warning: The type parameter VT should not be bounded by the final type String. Final types cannot be further extended. Do you know if there's a way to suppress this warning (Eclipse)? If you're wondering how I got to have this:

import java.util.ArrayList;
import java.util.List;

class A<T> {
T value;
B<? super T> b;

void method() {
    b.method(value,new ArrayList<T>());
}}

interface B<X> {
<VT extends X> VT method(VT p, List<VT> lst);
}

// works fine
class C implements B<Number> {
public <VT extends Number> VT method(final VT p, final List<VT> lst) {
    return p;
}}

// causes warning
class D implements B<String> {
public <VT extends String> VT method(final VT p, final List<VT> lst) {
    return p;
}}

// error: The type E must implement the inherited abstract method B<String>.method(VT, List<VT>)
class E implements B<String> {
@SuppressWarnings("unchecked")
public String method(final String p, final List<String> lst) {
    return p;
}}

Thanks! Cristian


回答1:


Your code doesn't compile, but here's something similar, which I assume is what you want:

class A<T>{
    T value;
    B<? super T> b;
    void method(){
        b.method(value);
    }
}
interface B<X>{
    <VT extends X> VT method(VT p);
}
// works fine
class C implements B<Number>{
    public <VT extends Number> VT method(VT p){return p;}
}
// causes warning
class D implements B<String>{
    public <VT extends String> VT method(VT p){return p;}
}

Seeing that you don't have a choice to saying extends String here, I'd say this is a bug in Eclipse. Furthermore, Eclipse can usually suggest an appropriate SuppressWarnings, but doesn't here. (Another bug?)

What you can do is change the return and argument type to String and then suppress the (irrelevant) type safety warning it causes:

// no warnings
class D implements B<String>{
    @SuppressWarnings("unchecked")
    public String method(String p){return p;}
}


来源:https://stackoverflow.com/questions/3957121/suppresswarnings-for-final-type-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!