简体   繁体   中英

How to convert a String which looks like an Array into an actual Object Array?

Since

public static String requestMethodExecution(String objectName, String className, String methodName, Object...
            params) {
        return String.format("%s,%s,%s,%s", objectName, className, methodName, Arrays.toString(params));
    }

returns a String, and if you would, for example, call the method like this:

requestMethodExecution("foo","bar","fooBar",2.0,3.0,"Hello");

You'd get a String like this: foo,bar,fooBar,[2.0,3.0,Hello]

I would love to iterate over that Array, but I can't since it is a String.

Reason behind this is this method: (I just started with reflection, so I do not know how else to do it)

 public static Class[] getParameterType(String ...params) throws ClassNotFoundException {
            Class[] paramTypes = new Class[params.length];
            for(int i=0; i<params.length;i++){
                Class paramClass = Class.forName(params[i]);
                if (paramClass == Double.class) {
                    paramTypes[i] = (double.class);
                } else if (paramClass == Integer.class) {
                    paramTypes[i] = (int.class);
                } else {
                    paramTypes[i] = paramClass;
                }
            }
            return paramTypes;
    }

So far I have only come up with a very dirty way:

 public static String[] getParams(String message){
    int indexOfParamStart = message.indexOf("[");
    int indexOfParamEnd = message.indexOf("]")+1;
    String[] splitMessage = message.substring(indexOfParamStart, indexOfParamEnd).replaceAll("\\[", "")
            .replaceAll("]", "").replaceAll(" ","").split(",");
    return splitMessage;
}

Edit: Thanks for looking into this! Since some of you are asking what I am trying to achieve, here is a bit more explanation:

I want to implement a simple request/reply protocol which allows remote method invocation (and I do not want to use java RMI...) So I listen for requests whose structure can be seen at the requestMethodExecution example.

There I have all the relevant information to call the Method upon my class, so to invoke the method I need it's arguments (and their value) and I do not know how to access them from the given String.

The others are easy with Class c = Class.forName(className); etc..

Edit#2: My question is not about a simple regex, so why close it? The title already states a different subject, I am getting a bit salty here...

看到此问题对于使用RegEx提取从外部串的排列体(由方括号中),然后就可以简单地使用String.split(",")到阵列本体分成数组项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM