作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试使用反射访问一个方法,其中一个参数是回调。回调类型是不同类类型的通用接口(interface)。这些类是@SystemApi
,可以通过反射访问。 Here是我正在使用上述说法的类(class)。
下面是我的示例代码:
String sClassName = "android.telephony.euicc.EuiccCardManager";
Class classToInvestigate = Class.forName(sClassName);
Class interfaceclass = classToInvestigate.getClasses()[0]; //android.telephony.euicc.EuiccCardManager.ResultCallback
Method getallprofiles = classToInvestigate.getDeclaredMethod("requestAllProfiles", String.class,Executor.class, interfaceclass);
getallprofiles.invoke(null,getEid(), AsyncTask.THREAD_POOL_EXECUTOR,null);
在上面的 invoke
签名中作为最后一个参数,我需要传递使用反射创建的回调,它等同于或类似于下面的回调示例。
ResultCallback<EuiccProfileInfo[]> callback =
new ResultCallback<EuiccProfileInfo[]>() {
@Override
public void onComplete(int resultCode, EuiccProfileInfo[] result) { }
};
interfaceclass
字段中的同一个实例中找到。@SystemApi
我未能/坚持用反射翻译上述回调逻辑。任何人都可以帮助我吗?
最佳答案
看来你需要创建一个代理类:
// that class you don't have access too. imagine that it is not here, it is just to show example signature of method we want to run.
interface Callback {
void run();
}
public static void main(String[] args) throws Exception {
Class<?> callbackClass = Class.forName("package.Callback");
Callback callback = Proxy.newProxyInstance(Main.class.getClassLoader(), new Class[]{callbackClass}, new CallbackInvocationHandler(() -> {
System.out.println("callback");
}));
callbackClass.getMethod("run").invoke(callback); // works!
}
static class CallbackInvocationHandler implements InvocationHandler {
private final Runnable myCallback;
CallbackInvocationHandler(Runnable myCallback) {
this.myCallback = myCallback;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("toString") && (method.getParameterCount() == 0)) {
// just random implementation
return proxy.getClass() + "@" + Integer.toHexString(System.identityHashCode(proxy));
}
if (method.getName().equals("hashCode") && (method.getParameterCount() == 0)) {
return System.identityHashCode(proxy);
}
if (method.getName().equals("equals") && (method.getParameterCount() == 1) && (method.getParameterTypes()[0] == Object.class)) {
return proxy == args[0];
}
if (method.getName().equals("run") && (method.getParameterCount() == 0)) {
// do what you want.
myCallback.run();
return null;
}
throw new IllegalStateException("Method not implemented: " + method);
}
}
但是如果你真的需要使用类似的东西——你做错事的可能性很大,难道你不能只添加对该项目的依赖吗?但是你不应该也依赖于系统类。
关于java - 如何在android中使用反射创建回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51397139/
我是一名优秀的程序员,十分优秀!