Pass the 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 a method that returns the following:

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

Is there a way so that I can use the toMap output for use in reverse order, for example:

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

I need to do something like

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

but I could not plan a way to do this

I also tried using 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 assume that due to type erasure, I get that the method is duplicated ...

any idea?

-

change

I forgot to indicate that I cannot change the reverse method, as many of them have suggested so far ...

+6
source share
3 answers

if you can change the method you want to call

 public static ActionDefinition reverse(String action, Map<String, ? extends Object> args) 
+8
source

Change the signature of the generic reuse method

 public static ActionDefinition reverse(String action, Map<String, ? extends Object> args) 
+4
source

Pass it simple (Map) , but be careful, you are cheating.

You can always refer it to Map , because it is one, and you can always combine the raw type into a method due to backward compatibility, so casting a parameterized type to raw is always a way to convert it to any other parameters. But you should do this only when you know that he will not introduce an error, and if you have no reasonable alternative.

+3
source

Source: https://habr.com/ru/post/887585/


All Articles