0

I'm working on a basic RPC design. From a listener, I retrieve a desired RPC like:

ArrayList<String> params = new ArrayList<String>();
params.add(Node.getLocal().getHostname());
params.add("test");
RPC rawRPC = StorageControl.getRPC(StorageControl.RPC_HelloMaster, params));

My StorageControl class is pretty simple right now,

public class StorageControl {
    public StorageControl(){
        availableRPCs.put(RPC_HelloMaster, new RPC("[%s] Hello, Master. [%s]"));
    }

    public static final String RPC_HelloMaster = "helloMaster";

    private static String MasterHostname;
    public static String getMaster(){ return MasterHostname; }
    public static void setMaster(String host){ MasterHostname = host; }

    private static Map<String, RPC> availableRPCs = new HashMap<String, RPC>();
    public static RPC getRPC(String key, ArrayList<String> params) {
        RPC rawRPC = availableRPCs.get(key);

        // This is what fails
        for (String param : params){
            rawRPC.msg = String.format(rawRPC.msg, param);
        }

        return rawRPC;
    }
}

RPC is just a simple class, containing a single variable, msg

So, the idea is that I want to retrieve RPCs, that may have a variable number of variables that need substituted. Is there a more elegant way (that actually works) to do this? What I have now fails with a MissingFormatArgumentException, I assume because the first loop doesn't attempt to replace beyond the 1st variable.

MrDuk
  • 16,578
  • 18
  • 74
  • 133

1 Answers1

1

At first we need to know how format works,

String x = String.format("%s %s","hello","world");

then x will have "hello world". But if we do this

String x = String.format("%s %s","hello"); 

It will give you a illegal argument exception because there are not enough arguments to replace.

So you need to pass all arguments at once. Now variable arguments actually array of args. So you can do this.

String stringToFormat = "%s %s %s";
String[] ags = {"hello","world","gg"};
stringToFormat = String.format(stringToFormat,ags);
System.out.println(stringToFormat);

In your case, you can just do this without loop

rawRPC.msg = String.format(rawRPC.msg, params.toArray(new String[params.size()]));
sabbir
  • 438
  • 3
  • 11
  • Do you of a built-in way to get the count of substitutions, so that I could compare beforehand? E.g., `"%s %s %s"` would be 3, so I'd want to compare that with `params.size()` – MrDuk Oct 26 '15 at 03:40
  • 1
    Check this answer for it http://stackoverflow.com/questions/767759/occurrences-of-substring-in-a-string – sabbir Oct 26 '15 at 03:53
  • Sure, I was mostly wondering if there was a built-in way to pull the count of tokens. Thanks though! – MrDuk Oct 26 '15 at 03:54