【发布时间】:2018-09-15 01:42:46
【问题描述】:
我正在尝试使用 Java 反射来调用将回调作为参数的方法。我使用 Java 反射实例化所有对象。另外,我使用Java Dynamic Proxy Class 作为回调参数。
我有几个奇怪的行为:
java.lang.reflect.Proxy.newProxyInstance()方法返回null-
以下类型的错误,取决于我尝试过的以下代码的不同版本:
Expected to unbox a 'int' primitive type but was returned nullExpected to unbox a 'String' primitive type but was returned null
这是我想作为 Java 动态代理类的匿名对象实例化的接口:
public interface MyListener {
void onEvent(String eventName);
}
这是我通过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");
}
关于callbackObject是否为null的日志消息似乎有冲突:
callbackObject=[null]
callbackObject is NOT null according to null check
根据Why does newInstance() return null?,newProxyInstance() 不可能返回 null,因为它从 newInstance() 获取值。
那么newProxyInstance() 的结果怎么可能是null 而不是null?像Expected to unbox a 'int' primitive type but was returned null 这样的错误消息是什么意思?
【问题讨论】:
标签: java android reflection