This question already has an answer here:
I have few class like this.
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();
}
}
}
And then I put them together into this
Async a = new Async();
a.bar("1", "2", new AsyncCallback() {
@Override
public void onComplete(Object response) {
System.out.println(response);
}
});
This works, outputting string "12" to stdout.
But when I tried adding new method using primitive type.
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});
}
}
And I tried using the new method.
a.foo(1, 2, 3, new AsyncCallback() {
@Override
public void onComplete(Object response) {
System.out.println(response);
}
});
It should return the string "3" to stdout. But instead it threw Exception
java.lang.NoSuchMethodException: Impl.foo(java.lang.Integer, java.lang.Integer, java.lang.Integer)
Why this happens and how to fix this?
Aucun commentaire:
Enregistrer un commentaire