Jin Kwon Jin Kwon - 3 months ago 21
Java Question

How can I define a generic method for Map<String, List<Object>> and MultivaluedMap<String, Object>?

I'm writing a http client library work for various platforms.(Java SE, Java EE)

With my Java SE implementation, I do

public void doSome(..., Map<String, List<Object>> params, ...);


With my Java EE implementation, I do

public void doSome(..., MultivaluedMap<String, Object> params, ...);


If I want to defined a generic abstract class for those methods, how can I define a method for both
Map<String, List<Object>>
and
MultivaluedMap<String, Object>
? Is there any elegant way to do this without a simple
T
?

Note that
Multivalued<K, V>
extends
Map<K, List<V>>
.

I, currently, am only capable of doing like this.

public abstract class AbstractClient {

public void doSome(..., Map<String, List<Object>> params, ...);
}


public class JavaEEClient extends AbstractClient {

static <K, V> MultivaluedMap<K, V> multivalued(Map<K, List<V>> map) {
if (map == null) {
return null;
}
if (map instanceof MultivaluedMap) {
return (MultivaluedMap<K, V>) map;
}
final MultivaluedMap<K, V> multi = new MultivaluedHashMap<>(map.size());
multi.putAll(map);
return multi;
}

public void doSome(..., MultivaluedMap<String, Object> params, ...) {
}

@Override
public void doSome(..., Map<String, List<Object>> params, ...) {
doSome(..., multivalued(params), ...);
}
}


UPDATE

I really have to admit that I'm miss-led myself. I actually started with JAX-RS only methods and started adding methods for Java SE with
URLConnection
.

It was O.K. with direct
MultivaluedMap
because
WebTarget
s and
Invocation
s accepts
MultivaluedMap
.

When I started adding classes and methods for
URLConnection
s, the problem arose.

I think I have to stick to
Map<String, List<Object>>
and use my
mutivalued
utility method.

Answer

If you say that MultivaluedMap<K, V> extends Map<K, List<V>> then you can just do:

public abstract class AbstractClass {

    public void doSome(..., Map<String, List<Object>> params, ...)
    ...
}

It will accept both MultivaluedMap and Map.

Comments