我有这个课:

public DrawItem {
    protected String getSeperator() {
        return "";
    }
    .......
    // some other methods
}


我还有另一个扩展DrawItem的类。

public DrawNumber extends DrawItem {
    @Override
    protected String getSeperator() {
        return "-";
    }
}


现在,在通用类CombinationGenerator<E>中,我试图实例化DrawItem / DrawNumber的对象。由于在Java中无法实例化泛型类型(如new E(...)),因此我根据this答案创建了一个Factory接口。

public interface DrawItemFactory<E> {
    E create(...);
}


然后在CombinationGenerator<E>类中,

public class CombinationGenerator<E> {
    DrawItemFactory<E> factory;

    public CombinationGenerator<E>(DrawItemFactory<E> factory) {
        this.factory = factory;
    }

    public List<E> generate() {
        ......
        list.add(factory.create(...));
        ......
    }
}


现在,DrawNumber类实现了DrawItemFactory<DrawItem>接口。

public DrawItem implements DrawItemFactory<DrawItem> {
    protected String getSeperator() {
        return "";
    }

    @Override
    public DrawItem create(...) {
        return new DrawItem(...);
    }
    .......
    // some other methods
}


我可以创建CombinationGenerator<DrawItem>类。

DrawItem drawItem = new DrawItem(...);
CombinationGenerator<DrawItem> generator = new CombinationGenerator<DrawItem>(drawItem);
List<DrawItem> combinations = generator.generate();


到目前为止,一切都很好。但是当我尝试创建这样的DrawNumber类时,

public DrawNumber implements DrawItemFactory<DrawNumber> {
     ....
}


它给了我以下错误:

The interface DrawItemFactory cannot be implemented more than once with different arguments: DrawItemFactory<DrawItem> and DrawItemFactory<DrawNumber>


我尝试了this解决方案,但遇到了相同的错误。还有其他方法吗?

最佳答案

不用使用所有这些工厂,您可以执行以下操作:

public class CombinationGenerator<E> {

    E instance;

    public CombinationGenerator(Class<E> clazz) {
        Constructor<?> con = clazz.getConstructor();
        this.instance = (E) con.newInstance();
    }
}


...
CombinationGenerator<DrawNumber> cg = new CombinationGenerator<DrawNumber>(DrawNumber.class);

关于java - 实例化通用类并实现通用接口(interface),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20716947/

10-10 05:37