Reputation: 3213
At first look it doesn't look like this might be possible so it would be good to hear some design patterns or a work around to make this work.
I need to provide an external library with the class literal Class<T>
in order for it to find the right type and annotations and pull from dynamodb. Here is the signature
public <T> T load(java.lang.Class<T> clazz, java.lang.Object hashKey)
However in my application needed class type is dynamic and gets resolved dynamically from the interface.
Here is an example where I resolve the class's full name dynamically from an interface.
String dynamoDBTypeName = getDynamoDBClassName(someInterface);
Class<?> clazz = Class.forName(dynamoDBTypeName);
and then I need convert clazz to class literal so it can be passed to
mapper.load(SomeClazz.class, hashKey)
I couldn't find a solution on how to convert a class object to a class literal so I can pass the actual type to the lib. Is there such one? Or is there a more elegant solution of dynamically resolving an interface to the class literal?
Upvotes: 0
Views: 292
Reputation: 59253
If I'm interpreting your intent correctly, then you can just do this:
String dynamoDBTypeName = getDynamoDBClassName(someInterface);
Class<?> clazz = Class.forName(dynamoDBTypeName);
Object loaded = mapper.load(clazz, hashKey);
Whether you get the class from Someclass.class or Class.forName(...), it's the same class object. The values of type parameters are only defined at compile time, so there is absolutely no difference in the information passed to mapper.load, the code that implements mapper.load, or the value that it returns.
The only difference is that if you pass a Class<X>
to mapper.load() then the compiler knows that it will return an X and you can assign it to a variable of type X without casting. If you pass a Class<?>
the compiler only knows that it will return an Object. It can be cast to an instance of the class by some code that knows what type it's supposed to be.
Upvotes: 1