在没有拆分包的情况下实现(编译时)插件架构 [英] Implementing a (compile-time) plugin architecture without split packages

查看:113
本文介绍了在没有拆分包的情况下实现(编译时)插件架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去的问题中,我询问了如何设计系统:

In a past question I asked how to design a system where:


  • 一个类包含一个或多个可选方法。

  • 可选方法由插件实现,编译时可能存在或不存在。

  • 如果用户在编译时调用其关联插件不存在的方法,则会出现编译时错误。

我提供了适用于Java 8的一种可能的解决方案

I provided one possible solution that works in Java 8.

不幸的是,这个解决方案取决于使用Java 9模块系统不允许的拆分包(导出相同包的两个模块)。

Unfortunately, this solution depends on the use of split packages (two modules exporting the same package) which are disallowed by the Java 9 Module System.

如何在Java 9中实现?

推荐答案

服务



如果我已正确理解了您正在使用的问题,那么您需要使用模块系统中的服务。

Services

If I have understood the question correctly what you're looking forward to using are Services from the module system.


Java长期以来通过 java.util.ServiceLoader
类支持服务,该类定位服务提供者在运行时通过搜索
类路径。

Java has long supported services via the java.util.ServiceLoader class, which locates service providers at run time by searching the classpath.

模块系统可以通过扫描模块中的类文件来识别服务的使用调用 ServiceLoader :: load 方法的工件。

The module system could identify uses of services by scanning the class files in module artifacts for invocations of the ServiceLoader::load method.

使用当前的项目结构,你应该定义一个抽象类接口,可以是在 guava中实现的扩展 core 模块类,由他们提供。

With your current project structure, you should define an abstract class or an interface that can be a extended of implemented in the guava, coremodule classes and is provided by them.

模块使用特定服务是该模块定义的一个重要方面,因此为了效率和清晰度,它在模块中表达带 的声明使用 子句:

A module uses a particular service is an important aspect of that module’s definition, so for both efficiency and clarity its expressed in the module’s declaration with a uses clause:

module com.foo.bar.sql {
    uses com.foo.Verifiers;
}

模块提供特定服务的实现同样重要,但是,这个在 提供 子句的模块声明中:

A module provides an implementation of a particular service is equally fundamental, however, this is put in the module’s declaration with a provides clause:

module guava {
    provides com.foo.Verifiers with com.guava. GuavaVerifier;
}

module core {
    provides com.foo.CoreVerifier with com.guava. GuavaVerifier;
}

这篇关于在没有拆分包的情况下实现(编译时)插件架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆