Implementing interface and abstract class with same methode name resulting in generic name clash

StackOverflow https://stackoverflow.com/questions/12109587

public interface Foo <T> {
   void setValue(T value);
}

public abstract class Bar extends JFormattedTextField{
    @Override
    public void setValue(Object value) {

    }
}

public class FooBar extends Bar implements Foo<String>{
    @Override //Foo
    public void setValue(String aValue) {
    // TODO Auto-generated method stub

    }

    @Override //Bar
    public void setValue(Object aValue) {
    // TODO Auto-generated method stub

}
}

This results in

Name clash: The method setValue(M) of type Foo has the same erasure as setValue(Object) of type JFormattedTextField but does not override it

Why do I get no love from the compiler and how could I fix it?

有帮助吗?

解决方案

This is because of type erasure (see this question: Java generics - type erasure - when and what happens)

In a nutshell: The compiler will use String to check that all method calls and type conversions work and then, it will use Object to generate the byte code. Which means you now have two methods with the same signature: public void setValue(Object aValue)

There is no perfect solution for this. You can make the code above compile by using Foo<Object> instead of Foo<String> but that's usually not what you want.

A workaround is to use an adapter:

public class FooBar extends Bar {
    public Foo<String> adapt() {
        return new Foo<String>() {
            public void setValue(String value) {
                FooBar.this.setValue( value );
            }
        }
    }
}

Basically what the adapt() method should do is create a new instance which implements the correct interface and which maps all method invocations to this.

其他提示

Java uses type erasure for generics. In your case type is String which Subclass of Object also. And your Bar class allows Object so Nameclash happens.

In your scenario because you are using a non generic legacy class with object as parameter in the extended class I will advice you to change method name or change type of Foo to String `Back to 1.4 days :-)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top