Java泛型中的接口实现传播

时间:2017-02-10 14:54:04

标签: java generics

我有以下代码(简化,以显示问题核心):

public interface IElement {}


public interface IDataSet<E extends IElement> {}


public interface IPropertyTranslator<D extends IDataSet<? super E>, E extends IElement> {}


public interface IElementTranslator<D extends IDataSet<?>> {}


public class AnimalElement implements IElement {}


public class AnimalDataSet implements IDataSet<AnimalElement> {}


public class AnimalPropertyTranslator implements IPropertyTranslator<AnimalDataSet, AnimalElement> {}


public class UniversalPropertyTranslator implements IPropertyTranslator<IDataSet<IElement>, IElement> {}


public class ElementTranslator<D extends IDataSet<? super E>, E extends IElement> implements IElementTranslator<D> {

    public Collection<IPropertyTranslator<? super D, ? super E>> propertyTranslators = new HashSet<>();

}


public class Demo {

    public static void demo() {
        ElementTranslator<AnimalDataSet, AnimalElement> animalElementTranslator = new ElementTranslator<>();
        animalElementTranslator.propertyTranslators.add(new AnimalPropertyTranslator());
        animalElementTranslator.propertyTranslators.add(new UniversalPropertyTranslator());
    }

}

不幸的是,演示方法的最后一行会产生以下错误:The method add(IPropertyTranslator<? super AnimalDataSet,? super AnimalElement>) in the type Collection<IPropertyTranslator<? super AnimalDataSet,? super AnimalElement>> is not applicable for the arguments (UniversalPropertyTranslator)。通过我发现的随机试验,问题可能与<D extends IDataSet<? super E>, E extends IElement>表达有关,虽然我仍然不知道如何修复它。

与此同时,代码的以下变量完美无缺:

public interface IDataSet {}


public interface IPropertyTranslator<D extends IDataSet> {}


public interface IElementTranslator<D extends IDataSet> {}


public class AnimalDataSet implements IDataSet {}


public class AnimalPropertyTranslator implements IPropertyTranslator<AnimalDataSet> {}


public class UniversalPropertyTranslator implements IPropertyTranslator<IDataSet> {}


public class ElementTranslator<D extends IDataSet> implements IElementTranslator<D> {

    public Collection<IPropertyTranslator<? super D>> propertyTranslators = new HashSet<>();

}


public class Demo {

    public static void demo() {
        ElementTranslator<AnimalDataSet> animalElementTranslator = new ElementTranslator<>();
        animalElementTranslator.propertyTranslators.add(new AnimalPropertyTranslator());
        animalElementTranslator.propertyTranslators.add(new UniversalPropertyTranslator());
    }

}

我不明白为什么接口的第二个通用部分导致代码行为不同。

1 个答案:

答案 0 :(得分:0)

该解决方案与“Producer Extends,Consumer Super”规则略有关系。在问题代码中,需要将以下标题更改为以下标题:

$locale = "ta_IN";

putenv("LANG=".$locale);
setlocale(LC_ALL, $locale);

$domain = "ta_IN";
echo bindtextdomain($domain, "Locale");
bind_textdomain_codeset($domain, 'UTF-8');

textdomain($domain);

echo  _("Username");

一切都会正常工作。