【发布时间】:2020-12-31 03:38:44
【问题描述】:
我目前有一个笨重的方法,它将采用一个包含方法名称和参数的字符串数组
String []wf = {"sobel(10,1)","sobel2(2,2)","sobelMax(sobel,100,10)"};
这告诉它要调用什么方法以及要传递的参数。但是,正如您所见,并非所有方法都使用相同数量的参数,并且并非所有参数类型都相同,有些是浮点数,有些是整数,有些是 PImage 类型。
目前这被传递给这个函数,它修剪字符串并提取有用的信息。然后通过 switch case 传递参数长度以最好地处理下一部分。
void workflow(String[] a){
String[] s = a;
for(int i=0;i<s.length;i++){
String s1 = s[i];
int [] pIndex = strIndex1(s1,"(",")");
String function = s1.substring(0,pIndex[0]);
String[]parameters = splitTokens(s[i].substring(pIndex[0]+1,pIndex[1]),",");
print("p",function ,"(");
for(int j=0;j<parameters.length;j++){
print(parameters[j]);
if(j<parameters.length-1)print(",");
}
println(")");
switch(parameters.length){
case 1: func1(function,int(parameters[0]));
println("c1");
break;
case 2: if(float(parameters[0])>-1000000&&float(parameters[0])<100000000){
func2(function,float(parameters[0]),int(parameters[1]));
println("c2");
}else {
Field field = null;
try{
field = this.getClass().getField(parameters[0]);
func2(function,field,int(parameters[1]));
}catch (NullPointerException e){
println("np c2");
}catch (NoSuchFieldException e) {
println("nsf c3");
}
}
break;
case 3:
if(float(parameters[0])>-1000000&&float(parameters[0])<100000000){
func3(function,float(parameters[0]),float(parameters[1]),int(parameters[2]));
println("c2");
}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("np c3");
}catch (NoSuchFieldException e) {
println("nsf c3");
}catch (IllegalAccessException e) {
println("ia c3");
}
}
println("c3");
break;
//func3(function,parameters);
//case 3: func4(function,parameters);
}
}
};
最后,switch 语句将方法和参数相应地路由到一个能够匹配类中正确方法的函数。
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("result",result);
} catch (SecurityException e) {
println(function , "se f1");
}catch (NoSuchMethodException e) {
println(function , "nsm f1");
}
catch (IllegalAccessException e) {
println(function , "ia f1");
}
catch (InvocationTargetException e) {
println(function , "it f1");
}
};
有没有办法可以压缩这段代码,也许可以取消 switch case 语句,因为它看起来很笨拙,而且参数越多,大小只会增加。
非常感谢
【问题讨论】:
标签: java reflection parameters field invoke