问题是你很难连接你的依赖。所以你的代码需要为第三方库做一些imports。您需要的是松散地耦合第三方库,以便您的应用程序的核心不需要导入任何与第三方库相关的内容。使用定义一个方法或一组方法的接口,以生成任何格式的报告。将此接口作为核心应用程序的一部分。然后,特定于格式的实现在依赖于您的核心应用程序和第 3 方库的单独模块中进行。在核心应用程序中使用工厂在运行时使用反射加载特定实现。如果请求的格式在类路径中不存在相关模块 jar,则会抛出 ClassNotFoundException,捕获并相应地处理。
这里是您的应用程序的示例结构
核心应用
class ReportData {
}
interface ReportGenerator {
byte[] generate(ReportData data);
}
class ReportGeneratorFactory {
public ReportGenerator getInstance(String format)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
ReportGenerator reportGenerator = null;
if("txt".equals(format)) {
reportGenerator = (ReportGenerator)
Class.forName("com.foo.TxtReportGenerator").newInstance();
} else if("html".equals(format)) {
reportGenerator = (ReportGenerator)
Class.forName("com.foo.HtmlReportGenerator").newInstance();
} else if("xl".equals(format)) {
reportGenerator = (ReportGenerator)
Class.forName("com.foo.XlReportGenerator").newInstance();
} else {
throw new UnsupportedOperationException(
String.format("Unsupport format %s", format));
}
return reportGenerator;
}
}
Txt / Html 导出(如果不需要第 3 方库,可以作为核心应用程序的一部分)
class TxtReportGenerator implements ReportGenerator {
public byte[] generate(ReportData data) {
// TODO Auto-generated method stub
return null;
}
}
class HtmlReportGenerator implements ReportGenerator {
public byte[] generate(ReportData data) {
// TODO Auto-generated method stub
return null;
}
}
用于 XL 报告的模块(自己的 jar)(取决于您的核心应用程序和第 3 方库)
class XlReportGenerator implements ReportGenerator {
public byte[] generate(ReportData data) {
// TODO Auto-generated method stub
return null;
}
}
用法:
public static void main(String[] args)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
byte[] report = new ReportGeneratorFactory()
.getInstance("xl")
.generate(new ReportData());
}