我试图使用反射访问一个方法,其中一个参数是回调。回调类型是不同类类型的通用接口。这些类是@SystemApi,可以通过反射访问。这里是我正在与上述说法一起工作的班级。
下面是我的示例代码:
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。我在用reflection.Anyone翻译上面的回调逻辑时失败了/坚持了,这能帮我吗?
发布于 2018-07-18 09:43:15
似乎您需要创建一个代理类:
// 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);
}
}但是如果你真的需要使用这样的东西--你做错了什么事的可能性很大,你就不能增加对这个项目的依赖吗?但是您不应该也依赖于系统类。
https://stackoverflow.com/questions/51397139
复制相似问题