Home > Software design >  What is the Java idiomatic way to deduce generic object class based on string/enum or class property
What is the Java idiomatic way to deduce generic object class based on string/enum or class property

Time:04-24

I'm using an API from an external Maven dependency with the following signature:

public <T> T get(String key, Class<T> responseType)

the API returns an object of type T for a given key from a key value store.

In my application there're several object types which can be returned, for example: Product, Customer etc.

I'd like to wrap the external API into my service which will receive a key and will return the object found. I can't figure out though how to return the object type from the service. Below is my attempt:

public class MyService {
      public <T> T get(String key, String objType) {
        Class clazz = null;
        if (objType == "Customer") {
            clazz = Customer.class;
        } else if (objType == "Product") {
            clazz = Product.class;
        }

        return externalApi.get(key, clazz); // doesn't compile
    }
}

This code doesn't compile because of Incompatible types: Object is not convertible to T error.

How can I properly pass responseType to externalApi.get and return the correct type without reflection?

CodePudding user response:

As the OP may have guessed, this is inherently impossible.

If the call site for get could do anything useful to preserve the returned type, T, then it would know the type anyway and could supply the correct class (providing this is transitively propagated through call sites).

(Also note, the code uses == for String instead of equals or switch.)

  • Related