Java – is there a better way to handle passing multiple parameters to methods
I found myself doing a lot of things:
/**
* Redirect to a MVC controller&action
* @param controller
* @param action
*/
public void redirect(String controller,String action) {
redirect(controller,action,new HashMap<String,String>());
}
/**
* Redirect to a MVC controller&action with extra URL parameters
* @param controller
* @param action
* @param data
*/
public void redirect(String controller,String action,Map<String,String> data) {
String urlParameters = "";
for(String key : data.keySet()) {
urlParameters += "&" + key + "=" + data.get(key);
}
m_binder.putLocal("RedirectParams","IdcService=MVC_FRONTCONTROLLER&controller="+controller+"&action="+action + urlParameters);
}
To invoke the second method, I actually need to create a HashMap to add data to it. I wonder if there is a more convenient way to do this?
As you can see, I need to know the key and value, so varargs doesn't work (as far as I can see)
I am open to all ideas, including the use of reflection
Solution
I have written this convenient method for building maps It needs varargs and makes a map in pairs It is very convenient to create a simple map in the test code You need to make sure you get the right number of arguments, but I like it because it makes the code smaller
@SuppressWarnings("unchecked")
public static <K,V> Map<K,V> mapOf(K key,V value,Object... morePairs) {
Map<K,V> map = new HashMap<K,V>();
map.put(key,value);
for (int i=0; i<morePairs.length; i+=2) {
map.put((K)morePairs[i],(V)morePairs[i+1]);
}
return map;
}
You can then create a map using the following methods:
Map<String,String> map = mapOf("One","1","Two","2");
However, this is not everyone's cup of tea (due to the lack of type safety), so you can change the implementation to pair:
Map<String,String> map = mapOf(pair("One","1"),pair("Two","2"));
Define pair as a static method, create a simple object with two values, and then convert mapof to entries in the map
