看看java.util.ServiceLoader类.
一般来说,这个想法是:
API罐
>提供接口
>使用ServiceLoader类来查找实现
装订/司机罐
>实现界面
>创建文件Meta-INF /并指定实现它的类名
javadoc中有一个很好的例子:
API罐
package com.foo;
public interface FooInterface { ... }
public class FooInterfaceFactory {
public static FooInterface newFooInstance() {
ServiceLoader loader = ServiceLoader.load(FooInterface.class);
Iterator it = loader.iterator();
// pick one of the provided implementations and return it.
}
装订罐
package com.myfoo;
public class MyFooImpl implements FooInterface { ... }
Meta-INF/com.foo.FooInterface
com.myfoo.MyFooImpl
编辑
SPI示例
public interface FooSpi {
void accepts(String url);
FooInterface getFooInstance();
}
public class FooInterfaceFactory {
public static FooInterface getFooInterfaceInstance(String url) {
ServiceLoader loader = ServiceLoader.load(FooSpi.class);
Iterator it = loader.iterator();
while (it.hasNext()) {
FooSpi fooSpi = it.next();
if (fooSpi .accepts(url)) {
return fooSpi.getFooInstance();
}
}
return null;
}
}
当然,将文件名更改为com.foo.FooSpi并提供FooSpi的实现.这将允许您将公共API与Spi界面隔离开来.
如果你想隐藏接受方法,你可以永远有一个第二个接口,这是你的公共API,而t