请帮忙检查一下代码中的错误:package com.enmo.mdi.distributedcomputing.distributed; import java.util.function.Function; import java.lang.reflect.*; public class Algorithm { public Algorithm() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { } private Double sum(Double... args) { Double num = 0.0; for (Double d: args){ num += d; } return num; } private String add(String... args) { StringBuilder str = new StringBuilder(); for (String s: args){ str.append(s); } return str.toString(); } public static Object callMethod(String name, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class<?> clazz = Class.forName("com.enmo.mdi.distributedcomputing.distributed.Algorithm"); // 获取方法的Method对象 Method method = clazz.getDeclaredMethod(name, Double.class); method.setAccessible(true); // 调用该方法 return method.invoke(null,args); } public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { // sum Double result = (Double) callMethod("sum", 1,2,3,4,5); System.out.println(result); String result1 = (String) callMethod("add", "1", "2", '3'); System.out.println(result1); } }
时间: 2024-02-14 12:07:46 浏览: 71
SensorTile开发套件及无线解决方案
代码中的问题是:
1. 在调用callMethod()方法时,传入的参数类型不匹配,应该将数字1,2,3,4,5修改为1.0,2.0,3.0,4.0,5.0,即将整型转换为浮点型。对于字符串"3",应该将其改为字符'3'。
2. 在调用callMethod()方法时,获取方法的Method对象时,应该使用Double[].class和String[].class而不是Double.class和String.class,因为参数是可变的数组。
修改后的代码如下:
```java
package com.enmo.mdi.distributedcomputing.distributed;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Algorithm {
public Algorithm() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
}
private Double sum(Double... args) {
Double num = 0.0;
for (Double d: args){
num += d;
}
return num;
}
private String add(String... args) {
StringBuilder str = new StringBuilder();
for (String s: args){
str.append(s);
}
return str.toString();
}
public static Object callMethod(String name, Object... args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<?> clazz = Class.forName("com.enmo.mdi.distributedcomputing.distributed.Algorithm");
// 获取方法的Method对象
Method method = clazz.getDeclaredMethod(name, Double[].class);
method.setAccessible(true);
// 调用该方法
return method.invoke(null, (Object) args);
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// sum
Double result = (Double) callMethod("sum", 1.0, 2.0, 3.0, 4.0, 5.0);
System.out.println(result);
String result1 = (String) callMethod("add", "1", "2", "3");
System.out.println(result1);
}
}
```
阅读全文