【问题标题】:Creating instance of implementation in interface in static method?在静态方法的接口中创建实现实例?
【发布时间】:2017-04-26 15:53:41
【问题描述】:

最近我试图创建这样的东西:使用静态方法创建接口,该方法将返回实现该接口的类的实例。实现类将具有私有构造函数,并且接口将通过反射创建该类的实例。示例代码:

static Implementation getImplementation(){
    Constructor<Implementation> constructor = Implementation.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    return constructor.newInstance();
}

我省略了异常处理。 这段代码是否出于某种目的而有效,还是只是可怕的反模式?

【问题讨论】:

  • 它似乎不必要地将接口与实现联系起来。为什么不把createInstance 放在Implementation 类中?
  • 好吧,我想到这将强制其他人使用接口,而不是创建像 Impl impl = new Impl(); 这样的实现实例;因为实现类中的构造函数是私有的(好吧,只要他也不会反射)。

标签: java reflection constructor interface static-methods


【解决方案1】:

这通常使用抽象的ImplementationFactory 来完成,它提供了一个静态方法,例如

public static ImplementationFactory newInstance() { ... }

ImplementationFactory 然后有一个类似Implementation newInstance() 的方法。

例如,请参阅TransformerFactory.newInstance

有不同的方法来实现这一点。就像从META-INF/services 下的某个资源中读取实现类的名称一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2016-11-21
    相关资源
    最近更新 更多