I am trying to use Java Reflection to call a method which takes a callback as an argument. I instantiate all of the objects with Java Reflection. Also, I am using a Java Dynamic Proxy Class as the callback argument.
The weird thing is the java.lang.reflect.Proxy.newProxyInstance()
method returns null.
Here is the interface I want to instantiate as an anonymous object as a Java Dynamic Proxy Class:
public interface MyListener {
void onEvent(String eventName);
}
And here is how I instantiate the interface via newProxyInstance()
:
Object callbackObject = null;
try {
Class callbackClass = Class.forName("com.example.MyListener");
Class[] interfaceArray = new Class[]{callbackClass};
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("onMyEvent")) {
Log.d(TAG, "InvocationHandler.invoke onMyEvent");
}
return null;
}
};
callbackObject = java.lang.reflect.Proxy.newProxyInstance(
this.getClass().getClassLoader(),
interfaceArray,
invocationHandler);
}
catch (Throwable t) {
Log.e(TAG, "newProxyInstance got exception [" + t + "] caused by [" + t.getCause() + "]");
}
Log.d(TAG, "callbackObject=[" + callbackObject + "]");
if (null == callbackObject) {
Log.e(TAG, "callbackObject is null according to null check");
}
else {
Log.d(TAG, "callbackObject is NOT null according to null check");
}
The log messages seem to conflict about whether callbackObject is null:
callbackObject=[null]
callbackObject is NOT null according to null check
According to Why does newInstance() return null? it's not possible for newProxyInstance()
to return null because it gets the value from newInstance()
.
So how can the result of newProxyInstance()
be null
and not null
?
Aucun commentaire:
Enregistrer un commentaire