有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

循环内实例化的类型的java注入依赖项

在这种情况下,我想对Implementation使用依赖项注入:

public interface Implementable{[...]}
public class Implementation implements Implementable{[...]}

public class DummyClass()
{
    private List<Implementable> testList;
    public DummyClass()
    {
        testList = new ArrayList<Implementable>();
        for(int i = 0; i < 10; i++)
        {
            Implementable testVar = new Implementation(i);
            testList.add(testVar);
        }
    }
}

虽然我设法收集到了很多信息,但这是不可能的。既不是通过构造函数注入,也不是通过使用泛型。另外,我更喜欢不依赖外部库来实现这一点的本机解决方案


编辑: 任何解决方案都要求DummyClass不必知道InterfaceType的哪个实现将在循环中实例化

我曾考虑过使用泛型,但失败了,因为InterfaceType testVar = new T(i);是不允许的。另外,newInstance()方法不可行,因为构造函数需要参数。虽然这仍然是可能的,但它需要太多的反射(getConstructor)和类型安全性的损失,以满足我对干净方法的体验

我非常满意地听到,我试图实现的目标无法以任何值得推荐的方式实现。这个问题是希望我错过了一些东西


Edit2: 我试图采用与drewmoore提供的解决方案类似的解决方案,但遇到了一个我没有想到的缺陷

接口不声明构造函数的任何需求。使用此方法,我必须在接口的所有实现中使用相同的构造函数

这让我想到了构建器模式。这仍然与接口需要定义构建方法的警告相同,因此必须再次对如何构建所有实现提出要求

有没有其他方法可以延迟施工?也就是说,这种方法可以让我注入我想要使用的(public DummyClass(InterfaceType implementation))实现的实例,但只在循环中构造(或构建或初始化)它,然后它将返回自身的副本

但话说回来。我越来越觉得我想要达到的目标是不可能的。或者因为不合理的额外复杂性或强加的限制而不应该这样做。然后我可能更愿意接受这个类对实现的直接依赖,并感谢drewmoore的见解


共 (1) 个答案

  1. # 1 楼答案

    经过进一步思考,并受到drewmoore现在不幸删除的答案的启发,我得出以下结论:

    正如我在第二次编辑中所说,当我对使用界面来声明施工合同感到不安时,我现在意识到这正是情况所需要的。我的意思是能够在循环中以某种方式构造这个对象。因此,必须制定该循环所需的要求。当然,界面是这项工作的理想选择

    以最初的示例为例,我的解决方案如下所示:

    DummyClass dummyInstance = new DummyClass(new ImplementationProvider());
    
    ///////
    
    public interface Implementable{[...]}
    public class Implementation implements Implementable{[...]}
    
    public interface ImplementationProviderAware
    {
        public Implementable createImplementation(Integer counter);
    }
    
    public class ImplementationProvider implements ImplementationProviderAware
    {
        public Implementable createImplementation(Integer counter)
        {
            return new Implementation(counter);
        }
    }
    
    public class DummyClass(ImplementationProviderAware implementationProvider)
    {
        private List<Implementable> testList;
        public DummyClass()
        {
            testList = new ArrayList<Implementable>();
            for(int i = 0; i < 10; i++)
            {
                Implementable testVar = implementationProvider.createImplementation(i);
                testList.add(testVar);
            }
        }
    }