我这样的课很少。
interface AsyncCallback {
void onComplete(Object response);
}
class Impl {
public String bar(String i, String j) {
return i + j;
}
}
class Async {
private final Impl impl;
public Async() {
impl = new Impl();
}
public void bar(String i, String j, AsyncCallback callback) {
callAsync("bar", callback, new Object[]{i, j});
}
private Class[] getParamsClasses(Object[] params) {
ArrayList<Class> classes = new ArrayList<>();
for (Object param : params) {
classes.add(param.getClass());
}
return classes.toArray(new Class[classes.size()]);
}
private void callAsync(String methodName, AsyncCallback callback, Object[] params) {
try {
Thread.sleep(1000);
Class[] paramClasses = getParamsClasses(params);
Method methodToCall = impl.getClass().getMethod(methodName, paramClasses);
Object response;
response = methodToCall.invoke(impl, params);
callback.onComplete(response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
然后我把它们放在一起
Async a = new Async();
a.bar("1", "2", new AsyncCallback() {
@Override
public void onComplete(Object response) {
System.out.println(response);
}
});
这样可以输出字符串“12”到stdout。
但是当我尝试使用原始类型添加新方法时。
class Impl {
//new method
public int foo(int i, int j, int k) {
return i + j + k;
}
}
class Async {
//new method
public void foo(int i, int j, int k, AsyncCallback callback) {
callAsync("foo", callback, new Object[]{i, j, k});
}
}
我尝试使用新方法。
a.foo(1, 2, 3, new AsyncCallback() {
@Override
public void onComplete(Object response) {
System.out.println(response);
}
});
它应该将字符串“3”返回到stdout。但相反,它抛出了异常
java.lang.NoSuchMethodException: Impl.foo(java.lang.Integer, java.lang.Integer, java.lang.Integer)
为什么会发生这种情况以及如何解决这个问题?