In Java, if I have the following information: List.class, Map.class, Integer.class, and an instance foo of some Object. Is it possible to cast foo into List<Map<Integer, Integer>>? I suppose not due to type erasure, but wondering if there is another way to achieve something similar.
EDIT: To provide more context. I'm writing an application that is able to take a query (which is composed of an object and a metric) and outputs the desired metric. An example would be "the sum of the elements in a list". The client would need to write a provider that registers itself to the app and broadcasts that it is able to provide a certain metric type for some object type (e.g. sum for a list). The app, upon receiving the query will match up the correct provider and invoke the calculate method on it.
Without generics this is simple. The canonical type for any instance of an object is its class. So I would treat the objects in the query as an Object then using its class, find a provider that is able to provide for this instance of the object. Similar thing for metrics.
Now introducing generics...Suppose I define my metric f to be the sum of elements in a list if the elements are Integer and the product if the elements are Double. I would need 2 providers one that provides for List<Integer> and the other for List<Double>. But due to type erasure I cannot use the canonical type class directly. So I store the involved classes (List.class and Integer.class or List.class and Double.class) and match up the provider using tuples of classes.
Hence in the calculate method I need to perform a covariant cast from Object to the appropriate type that the provider handles.
Perhaps I'm taking the wrong approach to the problem?
The closest you'll get is this:
List<Map<Integer, Integer>> fooList = List.class.cast(foo);
It will produce a Compiler Warning because of unsafe casting and usage of raw types, but it is actually safe (if you know your Object to contain what it says it does).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With