Java 在静态方法的接口中创建实现实例?
最近我尝试创建类似这样的东西:使用静态方法创建接口,该方法将返回实现该接口的类的实例。实现类将具有私有构造函数,接口将通过反射创建该类的实例。此处的示例代码:Java 在静态方法的接口中创建实现实例?,java,reflection,constructor,interface,static-methods,Java,Reflection,Constructor,Interface,Static Methods,最近我尝试创建类似这样的东西:使用静态方法创建接口,该方法将返回实现该接口的类的实例。实现类将具有私有构造函数,接口将通过反射创建该类的实例。此处的示例代码: static Implementation getImplementation(){ Constructor<Implementation> constructor = Implementation.class.getDeclaredConstructor(); constructor.setAccessibl
static Implementation getImplementation(){
Constructor<Implementation> constructor = Implementation.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
静态实现getImplementation(){
构造函数=Implementation.class.getDeclaredConstructor();
constructor.setAccessible(true);
返回构造函数.newInstance();
}
我建议进行异常处理。
这段代码出于某种目的是有效的,还是仅仅是可怕的反模式?这通常是通过一个抽象的
实现工厂来完成的,它提供了一个静态方法,如
public static ImplementationFactory newInstance() { ... }
ImplementationFactory
然后有一个类似于Implementation newInstance()
的方法
例如,见
有不同的方法来实现这一点。就像从META-INF/services
下的某些资源中读取实现类的名称一样,它似乎不必要地将接口与实现绑定在一起。为什么不把createInstance
放在Implementation
类中呢?我想这会强制其他人使用接口,而不是创建Impl Impl=new Impl()之类的实现实例;因为实现类中的构造函数是私有的(好吧,只要他不使用反射)。