gpt4 book ai didi

java - 在运行时根据提供的依赖项动态创建 Java 类的实现

转载 作者:IT老高 更新时间:2023-10-28 20:46:39 32 4
gpt4 key购买 nike

我正在尝试根据运行时类路径中可用的类来确定创建类的新实例的最佳方法。

例如,我有一个库,它需要在多个类中解析 JSON 响应。该库有如下接口(interface):

JsonParser.java:

public interface JsonParser {
<T> T fromJson(String json, Class<T> type);
<T> String toJson(T object);
}

该类有多种实现方式,即GsonJsonParserJacksonJsonParserJackson2JsonParser,目前需要库的用户“pick “他们的实现将根据他们在项目中包含的库来使用。例如:

JsonParser parser = new GsonJsonParser();
SomeService service = new SomeService(parser);

我想做的是动态选择类路径上的库,并创建适当的实例,这样库的用户就不必考虑它(甚至不必知道另一个类的内部实现解析 JSON)。

我正在考虑类似于以下内容:

try {
Class.forName("com.google.gson.Gson");
return new GsonJsonParser();
} catch (ClassNotFoundException e) {
// Gson isn't on classpath, try next implementation
}

try {
Class.forName("com.fasterxml.jackson.databind.ObjectMapper");
return new Jackson2JsonParser();
} catch (ClassNotFoundException e) {
// Jackson 2 was not found, try next implementation
}

// repeated for all implementations

throw new IllegalStateException("You must include either Gson or Jackson on your classpath to utilize this library");

这是一个合适的解决方案吗?它看起来有点像 hack,并且使用异常来控制流程。

有没有更好的方法来做到这一点?

最佳答案

基本上你想创建自己的JsonParserFactory。我们可以在 Spring Boot framework 中看到它是如何实现的。 :

public static JsonParser getJsonParser() {
if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
return new JacksonJsonParser();
}
if (ClassUtils.isPresent("com.google.gson.Gson", null)) {
return new GsonJsonParser();
}
if (ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
return new YamlJsonParser();
}

return new BasicJsonParser();
}

所以您的方法几乎与此相同,除了使用 ClassUtils.isPresent method .

关于java - 在运行时根据提供的依赖项动态创建 Java 类的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239881/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com