简体   繁体   English

扩展 Java 类并强制现有库使用扩展类

[英]Extend a Java Class and force existing libraries to use the extended class

The situation is as follows: I'm using some libraries that use a specific class to load and access configuration parameters.情况如下:我正在使用一些使用特定类加载和访问配置参数的库。 The config loader class is implemented in one of the libraries.配置加载器类在其中一个库中实现。 What I did is: to extend the config loader class so that it fits my requirements and is able to load different config sources:我所做的是:扩展配置加载器类,使其符合我的要求并能够加载不同的配置源:

public class BetterConfigLoader extends OldConfigLoader {
    ...
}

Now I want to make the existing libraries use my compatible BetterConfigLoader without applying changes to the libraries or without the need to recompile them.现在我想让现有的库使用我兼容的 BetterConfigLoader,而不需要对库进行更改,也不需要重新编译它们。 Is there a way of best practice to accomplish this?有没有最佳实践方法来实现这一目标?

This depends on how your libraries refer to the configuration class.这取决于您的库如何引用配置类。 Do they have a hardcoded new OldConfigLoader().configure() ?他们有硬编码的new OldConfigLoader().configure()吗?

Or do they use some kind of SPI technique, eg checking for existence of a resource named META-INF/services/ConfigLoader , and only if not existing, falling back to the default configuration class?或者他们是否使用某种SPI技术,例如检查名为META-INF/services/ConfigLoader的资源是否存在,并且仅当不存在时才回退到默认配置类?

Instead of checking such a resource, they could as well check a System Property.除了检查这样的资源,他们还可以检查系统属性。 In these cases, you can set your special class by creating a matching SPI resource, or by setting the System Property.在这些情况下,您可以通过创建匹配的 SPI 资源或设置系统属性来设置您的特殊类。

In case of hardcoded reference, you are out of luck.如果是硬编码参考,那你就不走运了。

Instead of extending OldConfigLoader you can replace it.您可以替换它,而不是扩展 OldConfigLoader。 Start with the source code of OldConfigLoader, change it to suit your needs and then make sure your version is higher in the classpath then the original.从 OldConfigLoader 的源代码开始,更改它以满足您的需要,然后确保您的类路径中的版本高于原始版本。 Make sure your implementation has the same classname and is in the same package as the original.确保您的实现与原始实现具有相同的类名并且在同一个包中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM