Create implementation of Java class dynamically based on provided dependencies at runtime
<p>I'm trying to determine the best way to create a new instance of a class based on which classes are available on the classpath at runtime.</p>

<p>For example, I have a library that requires a JSON response to be parsed in multiple classes. The library has the following interface:</p>

<p><code>JsonParser.java</code>:</p>

<pre><code>public interface JsonParser {
    &lt;T&gt; T fromJson(String json, Class&lt;T&gt; type);
    &lt;T&gt; String toJson(T object);
}
</code></pre>

<p>This class has multiple implementations, i.e. <code>GsonJsonParser</code>, <code>JacksonJsonParser</code>, <code>Jackson2JsonParser</code>, and currently, the user of the library is required to "pick" their implementation to be used based on which library they've included in their project. For example:</p>

<pre><code>JsonParser parser = new GsonJsonParser();
SomeService service = new SomeService(parser);
</code></pre>

<p>What I'd like to do, is dynamically pick up which library is on the classpath, and create the proper instance, so that the user of the library doesn't have to think about it (or even have to know the internal implementation of another class parses JSON).</p>

<p>I'm considering something similar to the following:</p>

<pre><code>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");
</code></pre>

<p>Would this be an appropriate solution? It seems kind of like a hack, as well as uses exceptions to control the flow.</p>

<p>Is there a better way to do this?</p>