将不同的变量传递给反射的 getMethod 方法并调用该方法。

huangapple go评论74阅读模式
英文:

passing different variables into a reflection getMethod and invoking said method

问题

String []wf = {"sobel(10,1)","sobel2(2,2)","sobelMax(sobel,100,10)"};

void workflow(String[] a) {
  for (String s1 : a) {
    int pIndexStart = s1.indexOf("(");
    int pIndexEnd = s1.indexOf(")");
    String function = s1.substring(0, pIndexStart);
    String[] parameters = splitTokens(s1.substring(pIndexStart + 1, pIndexEnd), ",");
    
    print("p", function, "(");
    for (int j = 0; j < parameters.length; j++) {
      print(parameters[j]);
      if (j < parameters.length - 1) print(",");
    }
    println(")");

    try {
      if (parameters.length == 1) {
        func1(function, int(parameters[0]));
        println("c1");
      } else if (parameters.length == 2) {
        float param1 = float(parameters[0]);
        if (param1 > -1000000 && param1 < 100000000) {
          func2(function, param1, int(parameters[1]));
          println("c2");
        } else {
          Field field = this.getClass().getField(parameters[0]);
          func2(function, field, int(parameters[1]));
        }
      } else if (parameters.length == 3) {
        float param1 = float(parameters[0]);
        if (param1 > -1000000 && param1 < 100000000) {
          func3(function, param1, float(parameters[1]), int(parameters[2]));
          println("c2");
        } else {
          Field field = this.getClass().getField(parameters[0]);
          PImage p = (PImage) field.get(this);
          func3(function, p, float(parameters[1]), int(parameters[2]));
        }
      }
    } catch (NoSuchFieldException | IllegalAccessException e) {
      println("Error:", e.getMessage());
    }
    println("c3");
  }
}

void func1(String function, int p) {
  println(function, p);
  try {
    Method method = this.getClass().getMethod(function, int.class);
    println(method);
    method.invoke(this, p);
  } catch (Exception e) {
    println("Error:", e.getMessage());
  }
}

Note: This condensed version of your code still maintains the same functionality as your original code, but it removes the switch-case statement by using nested if-else statements. It also simplifies some of the logic, but the fundamental structure remains similar. Keep in mind that proper error handling and handling of various cases are still crucial to ensure the code works as intended.

英文:

I currently have a clunky method which will take a string array containing method names and parameters like this

String []wf = {&quot;sobel(10,1)&quot;,&quot;sobel2(2,2)&quot;,&quot;sobelMax(sobel,100,10)&quot;};

this tells it what method to call along with the parameters to pass. However as you can see not all the methods use the same number of parameters and not all the parameter types are the same, some floats some ints and some PImage types.

currently this is passed into this function, which trims the strings and extracts the useful info. Then passes the parameter length through a switch case to best handle the next part.

void workflow(String[] a){
String[] s = a;
for(int i=0;i&lt;s.length;i++){
String s1 = s[i];
int [] pIndex = strIndex1(s1,&quot;(&quot;,&quot;)&quot;);
String function = s1.substring(0,pIndex[0]);
String[]parameters = splitTokens(s[i].substring(pIndex[0]+1,pIndex[1]),&quot;,&quot;);
print(&quot;p&quot;,function ,&quot;(&quot;);
for(int j=0;j&lt;parameters.length;j++){
print(parameters[j]);
if(j&lt;parameters.length-1)print(&quot;,&quot;);
}
println(&quot;)&quot;);
switch(parameters.length){
case 1: func1(function,int(parameters[0]));
println(&quot;c1&quot;);
break;
case 2: if(float(parameters[0])&gt;-1000000&amp;&amp;float(parameters[0])&lt;100000000){
func2(function,float(parameters[0]),int(parameters[1]));
println(&quot;c2&quot;);
}else {
Field field = null;
try{
field = this.getClass().getField(parameters[0]);
func2(function,field,int(parameters[1]));
}catch (NullPointerException e){
println(&quot;np c2&quot;);
}catch (NoSuchFieldException e) {
println(&quot;nsf c3&quot;);
}
}
break;
case 3: 
if(float(parameters[0])&gt;-1000000&amp;&amp;float(parameters[0])&lt;100000000){
func3(function,float(parameters[0]),float(parameters[1]),int(parameters[2]));
println(&quot;c2&quot;);
}else {
Field field = null;
try{
field = this.getClass().getField(parameters[0]);
//Object.value = field.
PImage p = (PImage)field.get(this);
func3(function,p,float(parameters[1]),int(parameters[2]));
}catch (NullPointerException e){
println(&quot;np c3&quot;);
}catch (NoSuchFieldException e) {
println(&quot;nsf c3&quot;);
}catch (IllegalAccessException e) {
println(&quot;ia c3&quot;);
}
}
println(&quot;c3&quot;);
break;
//func3(function,parameters);
//case 3: func4(function,parameters);
}
}

};

finally the switch statement routes the methods and parameters accordingly to a function which will be able to match the correct method in the class.

void func1(String function,int p){
println(function,p);
Method method = null;
try {
method = this.getClass().getMethod(function,int  .class);
println(method);
method.invoke(this, p);
//println(&quot;result&quot;,result);
} catch (SecurityException e) {
println(function , &quot;se f1&quot;);
}catch (NoSuchMethodException e) {  
println(function , &quot;nsm f1&quot;);
}
catch (IllegalAccessException e) {  
println(function , &quot;ia f1&quot;);
}
catch (InvocationTargetException e) {  
println(function , &quot;it f1&quot;);
}

};

is there a way I could condense this code and maybe do away with the switch case statement as it all looks pretty unwieldy and only increases in size the more parameter.

Many Thanks

答案1

得分: 1

尝试用以下代码替换switch语句:

Class<?>[] parameterClasses = new Class<?>[parameters.length];
Object[] parsedParameters = new Object[parameters.length];
for (int j = 0; j < parameters.length; j++) {
    parameterClasses[j] = getParameterClass(parameters[j]);
    parsedParameters[j] = parseParameter(parameters[j]);
}
try {
    Method method = this.getClass().getMethod(function, parameterClasses);
    method.invoke(this, parsedParameters);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    throw new RuntimeException(e);
}

其中:

Object parseParameter(String parameter) {
    try {
        return Integer.parseInt(parameter);
    } catch(NumberFormatException e) {
        try {
            return Float.parseFloat(parameter);
        } catch(NumberFormatException e1) {
            try {
                Field field = this.getClass().getField(parameter);
                return field.get(this);
            } catch (NoSuchFieldException | IllegalAccessException e2) {
                throw new RuntimeException(e2);
            }
        }
    }
}

Class<?> getParameterClass(String parameter) {
    try {
        Integer.parseInt(parameter);
        return int.class;
    } catch(NumberFormatException e) {
        try {
            Float.parseFloat(parameter);
            return float.class;
        } catch(NumberFormatException e1) {
            return PImage.class;
        }
    }
}
英文:

Try to replace switch with

Class&lt;?&gt;[] parameterClasses = new Class&lt;?&gt;[parameters.length];
Object[] parsedParameters = new Object[parameters.length];
for (int j = 0; j &lt; parameters.length; j++) {
parameterClasses[j] = getParameterClass(parameters[j]);
parsedParameters[j] = parseParameter(parameters[j]);
}
try {
Method method = this.getClass().getMethod(function, parameterClasses);
method.invoke(this, parsedParameters);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}

where

Object parseParameter(String parameter) {
try {
return Integer.parseInt(parameter);
} catch(NumberFormatException e) {
try {
return Float.parseFloat(parameter);
} catch(NumberFormatException e1) {
try {
Field field = this.getClass().getField(parameter);
return field.get(this);
} catch (NoSuchFieldException | IllegalAccessException e2) {
throw new RuntimeException(e2);
}
}
}
}
Class&lt;?&gt; getParameterClass(String parameter) {
try {
Integer.parseInt(parameter);
return int.class;
} catch(NumberFormatException e) {
try {
Float.parseFloat(parameter);
return float.class;
} catch(NumberFormatException e1) {
return PImage.class;
}
}
}

huangapple
  • 本文由 发表于 2020年9月13日 11:47:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63866964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定