Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a Map<String, String> to a method requiring Map<String, Object>

I have a method with the following signature

public static ActionDefinition reverse(String action, Map<String, Object> args)

And I have method that returns the following:

public static Map<String, String> toMap(String value)

Is there some way I can cast the output of toMap to be used in reverse, something like:

ActionDefinition ad = reverse("Action.method", toMap("param1=value1,param2=value2"));

I'd need to do something like

(Map<String, Object>) toMap("param1=value1,param2=value2");

but I couldn't fin the way to do it

I also tried with the following method

public static Map<String, String> toMap(String value) {
    Map<String, Object> source = toMap(value);
    Map<String, String> map = new LinkedHashMap<String, String>();

    for(Map.Entry<String, Object> entry: source.entrySet()) {
        map.put(entry.getKey(), (String) entry.getValue());
    }

    return map;
}

but I guess that due to type erasure, I get that the method is duplicated...

any idea?

--

edit

I forgot to state that I can't change reverse method, as many have suggested so far...

like image 580
opensas Avatar asked May 09 '11 02:05

opensas


3 Answers

if you can change the method you wanna call to

public static ActionDefinition reverse(String action, Map<String, ? extends Object> args)
like image 118
ratchet freak Avatar answered Nov 15 '22 14:11

ratchet freak


Change the method signature of reverse to use generics

public static ActionDefinition reverse(String action, Map<String, ? extends Object> args)
like image 4
Kal Avatar answered Nov 15 '22 12:11

Kal


Cast it to simple (Map), but beware you are cheating.

You can always cast it to Map because it is one, and you can always feed a raw type into a method because of backwards compatibility, so casting a parametrized type to a raw one is always a way to convert it to any other parameters. But you should only do that when you know that it won't introduce a bug and if you have no sensible alternative.

like image 3
entonio Avatar answered Nov 15 '22 13:11

entonio