Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Unexpected Behaviour for Constructor <X,Y> (C<Y>) and Interface C<Y>

I have the following code:

A class that models the mapping between a ValueContainer<P> and an Entity E. (Eg. a checkbox (ValueContainer) and something that has a Boolean value):

public abstract class ObjValContainerMapper<E, P> {

    private ValueContainer<P> provider;

    public ObjValContainerMapper(ValueContainer<P> provider) {
        this.provider = provider;
    }

    public abstract P getValue(E entity);

    public abstract void setValue(E entity, P value);

    ...

}

An interface ValueContainer<P>:

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

A custom Checkbox:

public class AdvancedCheckBox extends JCheckBox implements ValueContainer<Boolean>

And some code that unexpectedly doesn't work:

AdvancedCheckBox chckbxBindToDrive = new AdvancedCheckBox(
            "Bind to Drive");

ObjValContainerMapper<IndexSpec, Boolean> bindToDriveMapper = 
        new ObjValContainerMapper<IndexSpec, Boolean>(chckbxBindToDrive) {
    @Override
    public Boolean getValue(IndexSpec entity) {
        if (entity == null) {
            return false;
        }
        return entity.isBindToDrive();
    }
    @Override
    public void setValue(IndexSpec entity, Boolean value) {
        entity.setBindToDrive(value);
    }
};

The code does not compile. The error shown is "The constructor ObjValContainerMapper(AdvancedCheckBox) is undefined". Eclipse suggests, among other options, to let AdvancedCheckBox implement ValueContainer or cast the argument chckbxBindToDrive to ValueContainer, despite AdvancedCheckBox explicitly declares implements ValueContainer<Boolean>. Strangely enough I have reused code from an old project that was built with Java 6, in which case the approx. same code worked fine. Has something changed with Java 7 or am I missing something?

Environment:

  • Eclipse Kepler
  • JDK 1.7.0_51
  • some code generated with WindowBuilder (the AdvacedCheckBox declaration)
like image 911
bfour Avatar asked Nov 10 '22 12:11

bfour


1 Answers

Thx for all the troubleshooting proposals in the comments.

The cause for this behaviour was that I copied the ValueContainer interface twice into two differnt packages as I assumed it would be missing given that Eclipse didn't seem to find it first (thx @sasankad for the proposal to clean the project). I hope this is still helpful for others as the error message and solution-proposals by the compiler and Eclipse respectively are not and are rather misleading.

like image 82
bfour Avatar answered Nov 14 '22 23:11

bfour